Class: PokerEngine::Cards

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/poker_engine/cards.rb

Constant Summary collapse

COLOR_BY_FIRST_LETTER =
{
  's' => Card::COLORS[:spade],
  'c' => Card::COLORS[:club],
  'h' => Card::COLORS[:heart],
  'd' => Card::COLORS[:diamond],
}.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cards) ⇒ Cards

Returns a new instance of Cards.



24
25
26
# File 'lib/poker_engine/cards.rb', line 24

def initialize(cards)
  @cards = cards
end

Instance Attribute Details

#cardsObject (readonly)

Returns the value of attribute cards.



22
23
24
# File 'lib/poker_engine/cards.rb', line 22

def cards
  @cards
end

Class Method Details

.parse(str_cards) ⇒ Object



12
13
14
15
16
17
18
19
20
# File 'lib/poker_engine/cards.rb', line 12

def self.parse(str_cards)
  cards = str_cards
          .split(',')
          .map do |str|
            Card.new str.to_i, COLOR_BY_FIRST_LETTER.fetch(str[-1])
          end

  new(cards)
end

Instance Method Details

#+(other) ⇒ Object



36
37
38
# File 'lib/poker_engine/cards.rb', line 36

def +(other)
  Cards.new(cards + other.cards)
end

#combination(x) ⇒ Object



49
50
51
# File 'lib/poker_engine/cards.rb', line 49

def combination(x)
  cards.combination(x).map { |c| Cards.new(c) }
end

#each(&block) ⇒ Object



32
33
34
# File 'lib/poker_engine/cards.rb', line 32

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

#sortObject

TODO: Make it work with block, too



41
42
43
# File 'lib/poker_engine/cards.rb', line 41

def sort
  cards.sort_by(&:value)
end

#sorted_valuesObject



45
46
47
# File 'lib/poker_engine/cards.rb', line 45

def sorted_values
  cards.map(&:value).sort
end

#to_sObject



28
29
30
# File 'lib/poker_engine/cards.rb', line 28

def to_s
  cards.map(&:to_s).join(', ')
end

#values_desc_by_occurencyObject

Make descending order primary by occurency and secondary by value



54
55
56
57
58
59
60
61
62
# File 'lib/poker_engine/cards.rb', line 54

def values_desc_by_occurency
  values = cards.map(&:value)

  values.sort do |a, b|
    coefficient_occurency = (values.count(a) <=> values.count(b))

    coefficient_occurency.zero? ? -(a <=> b) : -coefficient_occurency
  end
end