variable vars

Hi

How can I set a variable variable-name?

i=100

eval "a#{i}=0"

a_100 works, =0 not.

Opti

I'm not sure why you want to do this, and it depends on your context but
you can do this with something like instance_variable_set

irb(main):003:0> i = 'a'
=> "a"
irb(main):004:0> j = 100
=> 100
irb(main):005:0> instance_variable_set("@#{i}_#{j}", 42)
=> 42
irb(main):006:0> instance_variables
=> [:@a_100]
irb(main):010:0> instance_variable_get(:@a_100)
=> 42
irb(main):020:0> instance_variable_set("@b_#{i}_#{j}", 99)
=> 99
irb(main):021:0> instance_variables
=> [:@a_100, :@b_a_100]
irb(main):022:0> @b_a_100
=> 99

-Raj

···

On Thu, Sep 9, 2021 at 11:38 PM Die Optimisten <inform@die-optimisten.net> wrote:

Hi

How can I set a variable variable-name?

i=100

eval "a#{i}=0"

a_100 works, =0 not.

Opti

Unsubscribe: <mailto:ruby-talk-request@ruby-lang.org?subject=unsubscribe>
<ruby-talk list: member options login page>

You can do

binding.local_variable_set :"a#{i}", 0

But I don't see any reason why you should do it. You have Arrays and Hashes.

···

On 9/10/21 8:36 AM, Die Optimisten wrote:

Hi

How can I set a variable variable-name?

i=100

eval "a#{i}=0"

a_100 works, =0 not.

Opti

Unsubscribe: <mailto:ruby-talk-request@ruby-lang.org?subject=unsubscribe>
<ruby-talk list: member options login page>