Created
March 28, 2014 18:08
-
-
Save thatrubylove/9839203 to your computer and use it in GitHub Desktop.
Functional/OO Deck of Cards in Ruby - Start of a series of articles for rubylove.io
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Rank = Struct.new(:rank, :value) do | |
def to_s; rank; end | |
end | |
Card = Struct.new(:rank, :suit) do | |
def to_s; "#{rank} of #{suit}"; end | |
end | |
class Deck | |
SUITS = %w(hearts clubs spades diamonds) | |
RANKS = %w(ace two three four five six seven | |
eight nine ten jack queen king) | |
attr_reader :cards | |
def initialize(shoe_size=1) | |
@cards = build_deck*shoe_size | |
end | |
private | |
def build_deck | |
all_ranks.flat_map {|rank| SUITS.flat_map {|suit| Card.new(rank,suit) } } | |
end | |
def all_ranks | |
RANKS.map.with_index {|rank, value| Rank.new(rank, value) } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment