2

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) }
1
  • 4
    I would really recommend setting @store.owner.items to be an array and make each element accessible with @store.owner.items[0]. Commented Feb 7, 2017 at 2:43

1 Answer 1

5
(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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.