In ruby I want to do roughly the following and have it print out “changed”:
class Whatever
def change_foo
@foo="changed"
end
end
@foo = "original"
o = Whatever.new
o.change_foo
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 change_foo 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 change_foo“. I’m specifically asking about the above scenario where I have no control over the original variable nor the way that change_foo 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 change_foo
@main.instance_variable_set("@foo","changed")
end
end
o = Whatever.new(self)
Late to the party, but you can pass the current context to the method, and then eval the operations on the instance variable in that specific context: