I'm using Curses to create a command line GUI with Ruby. Everything's going well, but I have hit a slight snag. I don't think Curses knowledge (esoteric to be fair) is required to answer this question, just Ruby concepts such as objects and inheritance.
I'm going to explain my problem now, but if I'm banging on, just look at the example below.
Basically, every Window instance needs to have .close called on it in order to close it. Some Window instances have other Windows associated with it. When closing a Window instance, I want to be able to close all of the other Window instances associated with it at the same time.
Because associated Windows are generated in a logical fashion, (I append the name with a number:
instance_variable_set(self + integer, Window.new(10,10,10,10)) ), it's easy to target generated windows, because methods can anticipate what assosiated windows will be called,
(I can recreate the instance variable name from scratch, and almost query it: instance_variable_get(self + integer).
I have a delete method that handles this. If the delete method is just a normal, global method (called like this:
delete_window(@win543) then everything works perfectly. However, if the delete method is an instance method, which it needs to be in-order to use the
self keyword, it doesn't work for a very clear reason; it can 'query' the correct instance variable perfectly well (
instance_variable_get(self + integer)), however, because it's an instance method, the global instances aren't scoped to it!
Now, one way around this would obviously be to simply make a global method like this:
delete_window(@win543). But I have attributes associated with my window instances, and it all works very elegantly.
This is very simplified, but it literally translates the problem exactly:
class Dog def speak woof end end def woof if @dog_generic == nil puts "@dog_generic isn't scoped when .woof is called from a class method!\n" else puts "@dog_generic is scoped when .woof is called from the global scope. See:\n" + @dog_generic end end @dog_generic = "Woof!" lassie = Dog.new lassie.speak #=> @dog_generic isn't scoped when .woof is called from an instance method!\n woof #=> @dog_generic is scoped when .woof is called from the global scope. See:\nWoof!
TL/DR: I need
lassie.speak to return this string:
"@dog_generic is scoped when .woof is called from the global scope. See:\nWoof!" @dog_generic must remain as an insance variable. The use of Globals or Constants is not acceptable.
Could woof inherit from the Global scope? Maybe some sort of keyword:
def woof < global # This 'code' is just to conceptualise what I want to do, don't take offence! end
Is there some way the .woof method could 'pull in' @dog_generic from the global scope? Will @dog_generic have to be passed in as a parameter?