I have a simple each statement on an array
game.each{|match| winner += rps_game_winner(match)
winner is previously defined as winner = []
rps_game_winner will return an array of 2 elements. I want the winner to be and array of an array of 2 elements. instead if game has 2 matches i will get an array for 4 elements.
Is there a way to quickly convert an array of 4 elements to an array with 2 arrays of 2 elements. Or to make winners an array of 2 elements in the first place
for example winners should equal [["rob","Hi"],["sally","no"]] instead of ["rob","Hi","sally","no"]
Don't use +=; use <<:
game.each{|match| winner << rps_game_winner(match)}
While + combines two arrays into one, << adds new elements. If a new element happens to itself be another array, it's still added as an element, not merged in.
If you prefer words to punctuation, you can also spell it push:
game.each do |match| winner.push(rps_game_winner match) end
Use each_cons, which means each consecutive elements:
game.each_cons(2){|match1,match2|
winner << [rps_game_winner(match1), rps_game_winner(match2)]
}
*NB: the use of each_cons works fine if rps_game_winner would return a flat element, not an array with two elements
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With