In ruby I want to do roughly the following and have it print out "changed":
class Whatever
def changeFoo
@foo="changed"
end
end
@foo = "original"
o = Whatever.new()
o.changeFoo()
puts "it changed" if @foo == "changed"
puts "it did not change" if @foo == "original"
The problem is, of course, that inside Whatever, @foo belongs to an instance of Whatever.
Is there a way to make changeFoo change the "global" foo? Another way of asking this might be "what object can I reference that "owns" @foo?".
I don't want solutions like "use a global variable" or "use a class variable" or "pass @foo to changeFoo()". I'm specifically asking about the above scenario where I have no control over the original variable nor the way that changeFoo() is called.
I have come up with a workaround where I pass in a reference to the global object at construction time, but I'm not crazy about it since it requires I instantiate Whatever at the proper scope.
class Whatever
def initialize(main)
@main = main
end
def changeFoo
@main.instance_variable_set("@foo","changed")
end
end
o = Whatever.new(self)