I’m looking to generate a dynamic variable such as the following:
varnum = rand(100000)
value = 5
instance_variable_set("@v" + varnum.to_s, value)
Now, in IRB, if the varnum returned 345 – you can deduce that the variable generated is @v345
However, running the code in a script – how would you be able to call it? Is there a way to patch a variable with something like @v + varnum.to_s ?
Well, if you ever wanted to access the variable again, you’d have to do one of two things:
Object#instance_variablesto get a list of instance variables, and take out only those that start withv.To access a variable once you still have it’s value, use this:
There is a deeper problem here though. You should never, ever, ever dynamically generate instance variables. If you need to access data through a random number as a part of an object, have one instance variable, say
@vs, which is a hash mapping random numbers to your value.