Skip to content

Instantly share code, notes, and snippets.

@0x0dea
Created July 23, 2015 20:56
Show Gist options
  • Save 0x0dea/5eb9c574b790af39bf16 to your computer and use it in GitHub Desktop.
Save 0x0dea/5eb9c574b790af39bf16 to your computer and use it in GitHub Desktop.
class Card
attr_reader :value
def initialize rank
@rank = rank
@value = case rank
when ?A then 11
when /[TJQK]/ then 10
else rank.to_i
end
end
def ace?
@rank == ?A
end
end
class Hand
def initialize *cards
@cards = cards.map(&Card.method(:new))
end
def << card
@cards << card
end
def value
val = @cards.map(&:value).reduce(:+)
val -= 10 * @cards.count(&:ace?) if val > 21
val
end
end
h = Hand.new
h << Card.new(?A)
h << Card.new(?K)
p h.value
h << Card.new(?A)
p h.value
p Hand.new(?Q, ?Q).value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment