BasicObject.class_eval do
def instance(ins)
eval "@#{ins}=#{ins}", binding
end
end
Is the code in question. What I want it to do is in the following code, create a new instance variable, bar, inside class Foo.
What I get after running this code:
class Foo
bar = 3
end
Foo.instance(:bar)
is:
NameError: undefined local variable or method `bar for Foo:Class
from /Users/Solomon/Desktop/Ruby/instance.rb:3:in `instance'
from /Users/Solomon/Desktop/Ruby/instance.rb:3:in `eval'
from /Users/Solomon/Desktop/Ruby/instance.rb:3:in `instance'
Why is this happening.
Couple things here….You have defined an instance method
instanceforBasicObject. You are then calling this instance method on theFooobject. The Foo object is a class. You have not set any instance variables for the Foo object. You set an instance variable with the@sign.All that the
instancemethod does is set the instance variable @ins to itself.The
, bindingis not needed here either asbindingis a top level method that returns the current variable bindings. You only need to save abindingif you need to pass around a saved “environment”. Having, bindingdoes not hurt anything but is redundant.