alisontague alisontague - 1 year ago 56
Ruby Question

Ruby dynamically assign numbered variables

I cant find a similar question, but I'm sure it's out there somewhere so please point me in the direction if it is. I'm writing an rspec test and want to dynamically assign 9 variables.

The long way to do it:

@store.owner.item1 = (Faker::Lorem.word)
@store.owner.item2 = (Faker::Lorem.word)
@store.owner.item3 = (Faker::Lorem.word)
@store.owner.item4 = (Faker::Lorem.word)
@store.owner.item5 = (Faker::Lorem.word)
@store.owner.item6 = (Faker::Lorem.word)
@store.owner.item7 = (Faker::Lorem.word)
@store.owner.item8 = (Faker::Lorem.word)
@store.owner.item9 = (Faker::Lorem.word)


Something close to what I'm looking for (does not work):

(1..9).each { |number| @store.owner.send("item#{number}") = (Faker::Lorem.word) }

Answer Source
(1..9).each { |number| @store.owner.send("item#{number}=", Faker::Lorem.word) }

you can send item6 or item6= both are methods of owner. If you send a method that needs its own parameter (as item6= does) then the next parameter of the send method is the parameter to send to the method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download