Wednesday, July 14, 2010

Dynamic variable names

Here is a way of dynamically setting instance variable names in ruby. So as in given example you can use @a, @b et. al. w/o first defining them.

def funcA
new_hash = {:a=>'A',:b=>'B',:c=>'C',:d=>'D'}
new_hash.each{|k,v|
instance_var = "@#{k}"
instance_variable_set(instance_var.to_sym, v)

}
end

funcA
puts @a


Actually, I wanted to iterate through a Settings table and create instance variables for all the settings available. Settings table has name and value columns to store admin settings. And I did not want to write a line for setting every instance variable.

It was simpler than i had thot

settings = Settings.find(:all)

settings.each{|setting|
instance_variable_set("@#{setting.name}","#{setting.value}")
}


Regards,
UVT

PS - I luv Ruby :-)

No comments:

Post a Comment