Multiple variables in one for - Rails
Fellas! I'm creating my first independent project in Rails 3. This is mostly for practice. I've run in a problem.
The site gonna be about tarot predictions. In a form I ask for the deck and spread formation. In the controller I grab this and put in some va开发者_开发问答riables. Than I have to list it out on the view.
The problem is: I have (for ex) 10 cards for 10 positions. I want to list one card description with one position description. In my solution I build an array for the position descriptions and put the cards in a for cycle. Than I shift out the positions from the array with every step of the for. In code:
<% for cardnum in @cardnums
@cp = @card_positions.shift
@card = Card.find_by_id(cardnum)
%>
Writing out the data
<% end %>
However I think there are far more nice and clever solutions.
Is that possible to do the for cycle on two variables? Or any other nice solution?
Yours, Kael
I do not exactly understand what you are trying to do, but
cycle on two variables
If you mean to iterate on two arrays at once, Array#zip can be helpful. You can do:
a = [1,2,3] # use card_position array
b = %w{a b c} # use cards array
c = a.zip(b) #=> [[1, "a"], [2, "b"], [3, "c"]]
# you can do
c.each do |cp, card|
# do something with card_position(cp) and card
end
精彩评论