views:

63

answers:

2

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.

+2  A: 

How about

deck.each_slice(@players.size) do |cardSet|
 @players.zip(cardSet).each {|player,card| player << card}
end
jason.rickman
Thanks, works perfectly.
Mk12
I just realized that there's no handling for running out of cards. You can pre-slice the deck to get an even number, or break early from the outer loop if you detect cardSet contains nil elements.
jason.rickman
jason.rickman
is there an easier way to do this if it doesn't need to be one by one?
Mk12
cardCount = 7; @players.each {|player| player.push *deck.shift(cardCount)}
jason.rickman
+2  A: 

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
Joshua Cheek
Thanks, this way is very clean and similar to what i originally intended.
Mk12