Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton class and instance variables

Tags:

ruby

eval

irb

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]
like image 348
mhaseeb Avatar asked May 06 '16 10:05

mhaseeb


2 Answers

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]
like image 158
Ilya Avatar answered Oct 28 '22 18:10

Ilya


If your goal is to set an instance variable programmatically, you can use:

a.instance_variable_set(:@var_one, 1)
like image 35
Wand Maker Avatar answered Oct 28 '22 20:10

Wand Maker