This has been covered elsewhere. I did it in the past, but of course life has a way of kicking out old info to make space for the new.
Without being too terribly long winded, I will say that the reason for making this post is due to the fact that when I wanted to figure out how to dynamically create variables with ruby, I did a google search for a number of derivations of: ruby programmatically creating variables. This came up with a lot of nothing. I quickly realized this was turning into one of those dreaded cases of having to know the method name you’re looking for before you can find it. I’m a bit embarrassed to say I didn’t check this one, but thanks to blink on #ruby-lang, I’m posting just incase someone else searches with the same terms.
So at its very simplest:
eval "ans = 42"
Read more about eval at Jim Weirich’s always excellent blog.
Furthermore, instance variables of a class can be set via set_instance_variable.
class DeepThought
end
question = DeepThought.new
question.instance_variable_set("@ans", 42)
def question.what_is_the_answer
return @ans
end
question.what_is_the_answer
=> 42
question.what_is_the_answer => 42
Erm, that’s a pretty weird final answer to the question that was asked!
Oof! Shouldn’t blog after all-nighters :)
Found myself in the same place. Thanks!