Reputation: 26404
I'm having trouble finding a nice elegant ruby way to do this. I have a deck array with 52 Card
objects, and I want to iterate over it and loop through an array of Player
objects, dealing one card at a time into their hand array. Something like:
deck = Card.deck.shuffle!
deck.each do |card|
@players.NEXTELEMENT.hand << card
end
where NEXTELEMENT
would yield the next element and return to the start of the array on encountering the end. I tried adding a method like this to Array, but I got a LocalJumpError.
Thanks.
Upvotes: 1
Views: 675
Reputation: 31756
Just mod which card you are at by the number of players.
num_players = @players.size
deck.each_with_index do |card,index|
@players[ index % num_players ].hand << card
end
Upvotes: 3
Reputation: 15211
How about
deck.each_slice(@players.size) do |cardSet|
@players.zip(cardSet).each {|player,card| player << card}
end
Upvotes: 2