Why does the instance_variables
method not show @var_one
against the variable a
?
a = Object.new
def a.my_eval; yield end
a.my_eval { @var_one = 1 }
a.instance_variables
# => []
instance_variables
# => [@var_one]
You should use instance_eval
:
a.instance_eval { @var_one = 1 }
=> 1
a.instance_variables
=> [:@var_one]
When you use ordinary eval
, you define your instance variable in context of current self
, if you do it in irb, it is the main
object:
a.eval { self }
=> main
So, you can modify your a.eval
method by executing a block in a context of an instance:
def a.eval(&block)
instance_eval &block
end
a.eval { @a = 1 }
=> 1
a.instance_variables
=> [:@a]
If your goal is to set an instance variable programmatically, you can use:
a.instance_variable_set(:@var_one, 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With