Frage

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.

War es hilfreich?

Lösung

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"]

Andere Tipps

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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top