life.i.think: Programmatically Naming and Creating Variables with Ruby

Programmatically Naming and Creating Variables with Ruby
Scribbled on March 2nd. 4 comments.

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

Comments

Leave a response

  1. GeorgeMarch 02, 2007 @ 11:40 PM

    question.what_is_the_answer => 42

  2. Paul McCannMarch 02, 2007 @ 11:41 PM

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

  3. BrittMarch 03, 2007 @ 03:50 AM

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

  4. dawnMarch 17, 2007 @ 02:57 AM

    Found myself in the same place. Thanks!