0

I have a user model with 5 fruits:

User
  fruit_1
  fruit_2
  fruit_3
  fruit_4
  fruit_5

Is it possible to do a for-each when inserting into the user model? Like

@fruits = ['apple','banana','orange','strawberry','blueberry']

user = User.new

@fruits.each do |a, fruit |
  user.fruit_a = fruit <-- I want a to be the actual variable.
end
4
  • 2
    This is pretty confusing, could you expand on your question a bit please? Commented May 31, 2013 at 20:16
  • @matt, hungovered =) Expanded the q a bit. More clear? Commented May 31, 2013 at 20:20
  • So are you trying to loop through fruit_1 to fruit_5 and assign them within a loop? Commented May 31, 2013 at 20:22
  • @cyle I have a array with 5 object which I want to assign to the fruits within the user model. Commented May 31, 2013 at 20:24

2 Answers 2

3
@fruits.each_with_index do |fruit, i|
  attrib = "fruit_#{i + 1}"
  user.send(attrib) = fruit
end
Sign up to request clarification or add additional context in comments.

2 Comments

That's the way. The "send" function executes the string it gets as an parameter as a command. BTW, having fruit1, fruit2 (...) seems like a bad design, but it's not the issue here :)
Yep, or simply, user.send("fruit_#{i+1}") = fruit inside the loop (cutting out the middle man ;)).
1

Here's an alternate syntax if you want:

user.assign_attributes(Hash[1.upto(@fruits.length).map{|i| ["fruit_#{i}", fruit[i]]}])

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.