I'm trying to grab two subarrays at a time within an array - any ideas on how to do this?
example:
deck = [[2,spades],[3,hearts],[6,diamonds],[10,clubs],[8,hearts],[9,clubs]]
Is there any way to grab two cards at a time with a loop, so the index would increase every time and go from [0..1] then [1..0] and so on to grab two cards at a time.
I'd like to put:
player 1 cards: [2,spades],[3,hearts]
player 2 cards: [6,diamonds],[10,clubs]
My recommendation would just be to pass the deck array in to a method and return an array with [player1, player2, deck]. If you're just drawing from the "top" of the deck, you can just use
shift
to take the first element out of the array.The Long Solution
I tried to be pretty detailed and not obfuscate this code much so it should read pretty explanatory.
You could make it a bit shorter by rewriting it like this, I just wanted it to be understandable what was happening:
The Condensed Solution
Be sure to include a
deck.shuffle
when you first generate the deck.Also, I don't know what you're using to generate the deck, but since I was having fun with it:
Generating A Shuffled Deck
Try this
How does this work?
each_slice(n)
cuts the array into pieces of lengthn
take(n)
takes the firstn
piecesYou could use
Enumerable::each_slice