문제

I am trying to generate all poker cards (52 of cards), here is how I do it:

ranks = '23456789TJQKA'.split ''
suits = 'SHDC'.split ''
my_deck = []

ranks.each do |r|
  suits.each { |s| my_deck << r+s }
end

my_deck # => ["2S", "2H", "2D", "2C", "3S", "3H", "3D", "3C", "4S", "4H", "4D", "4C", "5S", "5H", "5D", "5C", "6S", "6H", "6D", "6C", "7S", "7H", "7D", "7C", "8S", "8H", "8D", "8C", "9S", "9H", "9D", "9C", "TS", "TH", "TD", "TC", "JS", "JH", "JD", "JC", "QS", "QH", "QD", "QC", "KS", "KH", "KD", "KC", "AS", "AH", "AD", "AC"]

My friends who use python shows me this:

[r+s for r in '23456789TJQKA' for s in 'SHDC']

Does anyone could give me advice on how to make the above code more beautiful as the Python version? Thank you in advance.

도움이 되었습니까?

해결책

Another way to write this using Array#product:

ranks = %w(2 3 4 5 6 7 8 9 T J Q K A)
suits = %w(S H D C)

my_deck = ranks.product(suits).map(&:join)
#=> ["2S", "2H", "2D", "2C", "3S", "3H", "3D", "3C", "4S", "4H", "4D", "4C", "5S", "5H", "5D", "5C", "6S", "6H", "6D", "6C", "7S", "7H", "7D", "7C", "8S", "8H", "8D", "8C", "9S", "9H", "9D", "9C", "TS", "TH", "TD", "TC", "JS", "JH", "JD", "JC", "QS", "QH", "QD", "QC", "KS", "KH", "KD", "KC", "AS", "AH", "AD", "AC"]

다른 팁

It’s a matter of opinion. You could use %w() instead of the .split, more descriptive variable names, string interpolation, and the more idiomatic map rather than the iterative programming-esque eachs.

ranks = %w{2 3 4 5 6 7 8 9 T J Q K A}
suits = %w{S H D C}

my_deck = ranks.map{|rank| suits.map{|suit| "#{rank}#{suit}" }}.flatten
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top