mk12
mk12

Reputation: 26404

Ruby elegant way to deal card array to player objects

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

Answers (2)

Joshua Cheek
Joshua Cheek

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

jason.rickman
jason.rickman

Reputation: 15211

How about

deck.each_slice(@players.size) do |cardSet|
 @players.zip(cardSet).each {|player,card| player << card}
end

Upvotes: 2

Related Questions