Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying the contents of two arrays (not the arrays themselves)

I want to make an array with every card in the deck, so it would be ["Ac", "Ad", "Ah", "As", "Kc", ...] though order is not important.

Isn't there a way that inject could be used to solve this problem? This was as close as I could get.

cards = ["A", "K", "Q", "J", "T", "9", "8", "7", "6", "5", "4", "3", "2"] 
suits = ["c", "s", "d", "h"] 
ruby-1.9.2-p180 :025 > cards.inject(suits) { |suit, card| suit.map{|s| "#{card}#{s}"}}
 => ["23456789TJQKAc", "23456789TJQKAs", "23456789TJQKAd", "23456789TJQKAh"] 
like image 492
Jeremy Smith Avatar asked Jan 19 '23 13:01

Jeremy Smith


2 Answers

Is this what you aim to do?

cards.map { |card|
  suits.map { |suit| "#{card}#{suit}" }
}.flatten
like image 87
Iain Wilson Avatar answered Feb 22 '23 18:02

Iain Wilson


Or maybe something similar to

cards.product( suits ).map(&:join)
like image 44
christianblais Avatar answered Feb 22 '23 19:02

christianblais