只需在牌组中使用2-9。
在Ruby中创建套牌的首选和/或最有效方法是什么?
这是我下面的内容,或者我该怎么做/应该这样做?
deck = []
suits = ["spades", "diamonds", "clubs", "hearts"]
for x in suits
for y in 2..9
w = y.to_s
deck.push(w+" of "+x)
end
end
答案 0 :(得分:4)
我喜欢product
w / a block
a, suits = [], ["spades", "diamonds", "clubs", "hearts"]
suits.product((2..9).to_a) {|t,n| a << "#{n} of #{t}"}
答案 1 :(得分:2)
嗯,你可以使用地图:
suits = ["spades", "diamonds", "clubs", "hearts"]
deck = suits.map { |d| (2..9).map { |x| "#{x} of #{d}" } }.flatten
但效率大致相同。
答案 2 :(得分:2)
suits = ["spades", "diamonds", "clubs", "hearts"]
deck = suits.product((2..9).to_a).map { |x,y| "#{y} of #{x}" }
如果您想要所有52张卡片:
suits = ["spades", "diamonds", "clubs", "hearts"]
faces = { 1 => 'Ace', 11 => 'Jack', 12 => 'Queen', 13 => 'King' }
deck = suits.product((1..13).to_a).map { |x,y| "#{faces[y]||y} of #{x}" }
# => Ace of spades, 2 of spades, ..., King of spades, Ace of diamonds, etc.
答案 3 :(得分:1)
怎么样:
suits.flat_map {|s| (2..9).map{|r| "#{r} of #{s}"}}
答案 4 :(得分:0)
suits, values, deck = %w(spades hearts diamonds clubs), [*2..9], values.product(suits).map { |card| card * ' of ' }