Question

I would like to refactor the method full_deck in my Deck class. Instead of using nested each I would like to do it more elegantly. This method is returning an array with all cards in the deck:

 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
Was it helpful?

Solution

  def full_deck
    Card::RANKS.product(Card::SUITS).map { |arr| Card.new(*arr)}
  end

Untested, but I think that should work.

Edit: tested, and works :)

OTHER TIPS

You can do this even nicer using product method. 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 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top