bridge hands in ruby
A little while ago I started looking at Ruby and Ruby on Rails. So far I like what I see. I'm doing a little address book app to try rails and for the ruby side I'm solving pretty much random finger exercises like this one:
bridge hands.
require "enumerator"
Card = Struct.new(:suit, :face)
IS_PLAYER = /^[SWNE]$/
IS_CARDS = /^([CDSH][2-9TJQKA])+$/
PLAYERS = %w{S W N E}
SUITS = %w{C D S H}
FACES = %w{2 3 4 5 6 7 8 9 T J Q K A}
deck = nil
dealer = 0
ARGF.each_line() do |line|
line.chomp!
next if line.empty?
case line
when IS_PLAYER
deck = Array.new
dealer = PLAYERS.index(line)
when IS_CARDS
deck.concat(
line.enum_for(:each_byte).enum_slice(2).map do |sf|
Card.new(sf[0], sf[1])
end)
if deck.size == 52 then
hands = PLAYERS.inject(Hash.new) do |map, player|
map[player]= Array.new
map
end
deck.enum_slice(4).each do |round|
(0...4).each do |num|
hands[PLAYERS[(dealer + num + 1) % 4]] << round[num]
end
end
PLAYERS.each do |player|
hands[player] = hands[player].sort_by do |card|
SUITS.index(card.suit.chr) * FACES.size +
FACES.index(card.face.chr)
end
puts hands[player].inject(player + ":") { |string, card|
string + " " + card.suit.chr + card.face.chr
}
end
end
when "\#"
Kernel.exit(0)
else
Kernel.exit(1)
end
end
I'm still new in this ruby world so if you see some ruby idiom I'm missing or some awkward antipattern that I use feel free to correct me in comments.
Posted by Uwe Hoffmann at
05:05 PM