Tuesday, February 16, 2010

Dynamic creation of variables in ruby

by Sandip Ransing 0 comments

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 

blog comments powered by Disqus

About The Author

Sandip is a ruby on rails developer based in pune and also a blogger at funonrails. Opensource contributor and working with Josh software Private Limited. for more info read Follow Sandip on Twitter for updates.

Connect With Me...

Github Projects

@sandipransing Twitter