Forum: Ruby Referencing Variables By Name in a String

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Michael S. (Guest)
on 2009-03-05 23:27
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}"
      <something here to get a reference to the variable named in box>
      <now start the code referencing this item>
   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
Sharagoz -. (Guest)
on 2009-03-06 01:27
Is this what you're looking for?

1.upto(8) do |i|
  box = eval("pauseBox" + i.to_s)
  #do stuff with box
end
Michael S. (Guest)
on 2009-03-06 01:38
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
Rafael G. (Guest)
on 2009-03-08 21:30
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
badboy (Guest)
on 2009-03-08 21:37
(Received via mailing list)
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, ...)
This topic is locked and can not be replied to.