Class: RubyCards::Hand

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cards = []) ⇒ Hand

Initializes a hand of cards

Parameters:

  • cards (Array<Card>) (defaults to: [])

    A predetermined array of cards



19
20
21
22
23
24
# File 'lib/rubycards/hand.rb', line 19

def initialize(cards = [])
  @cards = []
  cards.each do |card|
    self << card
  end
end

Instance Attribute Details

#cardsObject (readonly)

Returns the value of attribute cards.



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

def cards
  @cards
end

Instance Method Details

#draw(deck, n = 1) ⇒ Hand

Draws n cards from a given deck and adds them to the Hand

Parameters:

  • deck (Deck)

    The deck to draw from

  • n (Integer) (defaults to: 1)

    The amount of cards to draw

Returns:

  • (Hand)

    The new hand



39
40
41
42
43
44
# File 'lib/rubycards/hand.rb', line 39

def draw(deck, n = 1)
  n.times do
    @cards << deck.draw unless deck.empty?
  end
  self
end

#each(&block) ⇒ Enumerator

Returns an enumator over the hand

Parameters:

  • block (Proc)

    The block to pass into the enumerator

Returns:

  • (Enumerator)

    An enumerator for the hand



57
58
59
# File 'lib/rubycards/hand.rb', line 57

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

#inspectString

A shortened representation of the hand used for the console

Returns:

  • (String)

    A concise string representation of the hand



71
72
73
# File 'lib/rubycards/hand.rb', line 71

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

#sort!Hand

Sorts the hand and returns it

Returns:

  • (Hand)

    The sorted hand



29
30
31
32
# File 'lib/rubycards/hand.rb', line 29

def sort!
  @cards.sort!
  self
end

#sumInteger

Returns the sum of the hand

Returns:

  • (Integer)

    The combined weights of the cards in the hand



49
50
51
# File 'lib/rubycards/hand.rb', line 49

def sum
  this.cards.reduce { |memo, card| memo + card.to_i }
end

#to_sString

Displays the hand using ASCII-art-style cards

Returns:

  • (String)

    The ASCII representation of the hand



64
65
66
# File 'lib/rubycards/hand.rb', line 64

def to_s
  @cards.map(&:to_s).inject(:next)
end