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 > car开发者_StackOverflow社区ds.inject(suits) { |suit, card| suit.map{|s| "#{card}#{s}"}}
=> ["23456789TJQKAc", "23456789TJQKAs", "23456789TJQKAd", "23456789TJQKAh"]
Is this what you aim to do?
cards.map { |card|
suits.map { |suit| "#{card}#{suit}" }
}.flatten
Or maybe something similar to
cards.product( suits ).map(&:join)
This doesn't use inject
but thought worth mentioning: Array#product. See answer to similar question here
精彩评论