我想在我的Deck类中重构方法full_deck
。而不是使用嵌套的each
我想更优雅地做。这个方法返回一个包含套牌中所有牌的数组:
class Deck
def initialize(variation)
@variation = variation
@cards = []
end
def full_deck
Card::SUITS.each do |suit|
Card::RANKS.each do |rank|
@cards << Card.new(rank, suit)
end
end
@cards
end
end
class Card
attr_reader :rank, :suit
SUITS = [:hearts, :clubs, :spades, :diamonds]
RANKS = [:"2",:"3",:"4",:"5",:"6",:"7",:"8",:"9",:"10", :J, :Q, :K, :A]
ROYAL_RANKS = [:"10", :J, :Q, :K, :A]
def initialize(rank, suit)
@rank = rank
@suit = suit
end
end
答案 0 :(得分:2)
def full_deck
Card::RANKS.product(Card::SUITS).map { |arr| Card.new(*arr)}
end
未经测试,但我认为这应该有用。
编辑:测试,并且有效:)
答案 1 :(得分:2)
使用产品方法可以做得更好。 http://www.ruby-doc.org/core-2.0/Array.html#method-i-product
def full_deck
Card::RANKS.product(Card::SUITS).map { |card| Card.new(*card) }
end