Playing cards: Difference between revisions

m
→‎{{header|Ruby}}: some improvements and sample output
(ruby attempt)
m (→‎{{header|Ruby}}: some improvements and sample output)
Line 1,065:
{{works with|Ruby|1.8.7+}}
<lang ruby>class Card
# class constants
Suits = ["Clubs","Hearts","Spades","Diamonds"]
Pips = ["2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"]
 
# class variable (private)
@@value = {
"2" => 2, "3" => 3, "4" => 4, "5" => 5, "6" => 6,
"7" => 7, "8" => 8, "9" => 9, "10" => 10,
"Jack" => 11, "Queen" => 12, "King" => 13, "Ace" => 14,
}
attr_reader :pip, :suit
def initialize(pip,suit)
@pip = pip
@suit = suit
end
 
def to_s
"#{@pip} #{@suit}"
end
# allow sorting an array of Cards: first by suit, then by value
def <=>(card)
(@suit <=> card.suit).nonzero? or @@value[@pip] <=> @@value[card.pip]
end
end
 
class Deck
def initialize
Line 1,087 ⟶ 1,102:
end
end
 
def to_s
"[#{@deck.join(", ")}]"
end
 
def shuffle!
@deck.shuffle!
@deck.shiftself
end
 
def deal(*args)
@deck.shift(*args)
shuffle! # Do we really need this? (instance variables are already private)
@deck.shift
end
end</lang>
 
deck = Deck.new.shuffle!
puts card = deck.deal
hand = deck.deal(5)
puts hand.join(", ")
puts hand.sort.join(", ")</lang>
<pre>10 Clubs
8 Diamonds, Queen Clubs, 10 Hearts, 6 Diamonds, 4 Clubs
4 Clubs, Queen Clubs, 6 Diamonds, 8 Diamonds, 10 Hearts</pre>
 
=={{header|Smalltalk}}==
Anonymous user