Referencing Variables By Name in a String


#1

I can think of several (rather ugly) ways to accomplish this, but
thought I’d check here to see if there is a simpler way to do this. I’m
constantly amazed by the features in Ruby (I admit to only knowing a
relatively small subset of them)

Assume I have objects (created in autogenerated code that frequently
gets regenerated. I can’t change this part of the code directly
(QTRuby), so creating them in an array isn’t really an option.

The names of the variables are pauseBox1, pauseBox2, pauseBox3 …
pauseBox8.
There are several variable groups like this - this is only one of them.
I periodically have to apply a block of code to each of them in
sequence. They’re not in an array, so I can’t directly enumerate over
them. It would be kinda nice to be able to do something like:

1.upto(8) do |i|
box = “pauseBox#{i}”


end

Does anyone know a way to accomplish something like this. If not, I
probably have to put code in the derived class to create the arrays, but
this is going to look messy to say the least … there are a lot of
these items.

Thanks in advance
—Michael


#2

Is this what you’re looking for?

1.upto(8) do |i|
box = eval(“pauseBox” + i.to_s)
#do stuff with box
end


#3

Sharagoz – wrote:

Is this what you’re looking for?

1.upto(8) do |i|
box = eval(“pauseBox” + i.to_s)
#do stuff with box
end

Exactly. Thanks … I forgot about eval.

Appreciate it much.
—Michael


#4

Michael S. wrote:

Sharagoz – wrote:

Is this what you’re looking for?

1.upto(8) do |i|
box = eval(“pauseBox” + i.to_s)
#do stuff with box
end

Exactly. Thanks … I forgot about eval.

Appreciate it much.
—Michael

Would it be possible to do the same thing, but generating the variable
name?
i.e.
1.upto(8) do |i|
“pauseBox” + i.to_s = i + 1
#do stuff with box
end

This don’t work


#5

Rg Rg schrieb:

Appreciate it much.
This don’t work
hm…if you have several variables with names like pauseBox1,
pauseBox2, you did something wrong. For this Array exists.
If this is not an Option there are several other ways (const_get,
instance_variable_get, …)