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

5 responses


Do you want to comment?

Comments RSS and TrackBack Identifier URI ?

question.what_is_the_answer
=> 42

March 2, 2007 7:30 pm

Erm, that’s a pretty weird final answer to the question that was asked!

March 2, 2007 7:30 pm

Oof! Shouldn’t blog after all-nighters :)

March 2, 2007 7:30 pm

Found myself in the same place. Thanks!

March 2, 2007 7:30 pm

Just ran across this and noticed an error,

set_instance_variable should be instance_variable_set

google found you when I typed the wrong thing

Cheers

January 11, 2009 10:59 pm

Comment now!
















Trackbacks