Class: RubyCards::Deck

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Enumerable
Defined in:
lib/rubycards/deck.rb

Constant Summary collapse

RANKS =
[*2..10, 'Jack', 'Queen', 'King', 'Ace']
SUITS =
%w{ Clubs Diamonds Hearts Spades }

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Deck

Initializes a standard deck of 52 cards options:

:number_decks
eg. Deck.new(number_decks: 2)
will create 2 decks standard decks of 52
:exclude_rank
eg. Deck.new(exclude_rank: [2,'Jack'])
will exclude 8 cards of the 2 and Jack rank


28
29
30
31
32
33
34
35
36
37
38
# File 'lib/rubycards/deck.rb', line 28

def initialize(options={})
  @cards = []
  options[:exclude_rank] ||= []
  options[:number_decks] ||= 1

  options[:number_decks].times do
    (RANKS - options[:exclude_rank]).product(SUITS).each do |rank, suit|
      @cards << Card.new(rank, suit)
    end
  end
end

Instance Attribute Details

#cards ⇒ Object (readonly)

Returns the value of attribute cards.



9
10
11
# File 'lib/rubycards/deck.rb', line 9

def cards
  @cards
end

Instance Method Details

#cut!(index) ⇒ Deck

Cuts the deck and returns it

Parameters:

  • index (Integer) —

    The index of the card that will be cut

Returns:

  • (Deck) —

    The cut deck



52
53
54
55
# File 'lib/rubycards/deck.rb', line 52

def cut!(index)
  (0..index).each { @cards << @cards.shift }
  self
end

#each(&block) ⇒ Enumerable

Enumerates the deck

Parameters:

  • block (Proc) —

    The block to pass into the enumerator

Returns:

  • (Enumerable) —

    The deck enumerator



61
62
63
# File 'lib/rubycards/deck.rb', line 61

def each(&block)
  @cards.each(&block)
end

#inspect ⇒ String

Displays a shortened version of the #to_s method for use in the ruby console

Returns:

  • (String) —

    A shortened string output of the deck



76
77
78
# File 'lib/rubycards/deck.rb', line 76

def inspect
  "[ #{@cards[0..2].map(&:inspect).join ', '}, ..., #{@cards[-3..-1].map(&:inspect).join ', '} ]"
end

#shuffle! ⇒ Deck

Shuffles the deck and returns it

Returns:

  • (Deck) —

    The shuffled deck



43
44
45
46
# File 'lib/rubycards/deck.rb', line 43

def shuffle!
  @cards.shuffle!
  self
end

#to_s ⇒ String

Displays concise card representations in an array

Returns:

  • (String) —

    The concise string representation of the deck



68
69
70
# File 'lib/rubycards/deck.rb', line 68

def to_s
  "[ #{@cards.map(&:inspect).join ', '} ]"
end