Dynamic creation of variables in ruby

1. To create local variables in ruby dynamically.
Use eval method in ruby

ree-1.8.7-2010.01 > eval(“local=4”)
 => 4 
ree-1.8.7-2010.01 > p local
4
ree-1.8.7-2010.01 > eval(“local_#{1}=4”)
 => 4 
ree-1.8.7-2010.01 > puts local_1
4
2. To create & get instance variables dynamically in ruby.
instance_varaiable_set & instance_varaiable_get methods are provided and no need to do it using eval.
ree-1.8.7-2010.01 > (0..3).each do |i|
ree-1.8.7-2010.01 >     instance_variable_set(“@instance_#{i}”, i*i+1)
ree-1.8.7-2010.01 ?>  end
 => 0..3 
ree-1.8.7-2010.01 > @instance_0
 => 1 
ree-1.8.7-2010.01 > @instance_2
 => 5 
3. Dynamic constant variable creation in ruby
ree-1.8.7-2010.01 > class Example
ree-1.8.7-2010.01 ?>  end
 => nil 
ree-1.8.7-2010.01 > Example.const_set(‘A’,200)
 => 200 
ree-1.8.7-2010.01 > Example::A
 => 200 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.