HOWTO: Use Ruby-Poker

First install ruby-poker:

gem install ruby-poker

Create a PokerHand object using the cards in your hand. PokerHand takes either an array of the cards or a string with a space between each card.

hand1 = PokerHand.new("8H 9C TC JD QH")
hand2 = PokerHand.new(["3D", "3C", "3S", "13D", "14H"])

hand1 was instantiated using a string and hand2 was created with an array. The format for entering cards is ValueSuit where value is the numerical value of the card and Suit is the first letter of the card’s suit: Hearts = “H”, Spades = “S”, Clubs = “C”, Diamonds = “D”. For face cards you can use the first letter of its name or the card’s equivalent numerical value.

Ten = T or 10
Jack = J or 11
Queen = Q or 12
King = K or 13
Ace = A or 14

As of ruby-poker 0.2.0 face cards can only be created using letters.

Now that we have created our PokerHands we can find out what their rank is.

puts hand1.rank           #=> Straight
puts hand2.rank           #=> Three of a kind

Or compare the hands to see which one has a higher rank.

puts hand1 > hand2        #=> true

That covers the basic operations. As a bonus tip, if you want to compare more than two hands you can place them in an array and call Array#sort. After sorting, the last hand in the array is the winning hand.

hand3 = PokerHand.new("2H 4C 6D 8S TS")
puts hand3.rank           #=> High Card
puts [hand1, hand2, hand3].sort.last    #=> 8h 9c Tc Jd Qh (Straight)

Edited 01/21/08: Updated for ruby-poker 0.2.0

3 thoughts on “HOWTO: Use Ruby-Poker

  1. Costas

    Would be really swell if this library scored hand percentages too for assessing preflop hands:

    hand1 = PokerHand.new(['AD','3D']) hand2 = PokerHand.new(['AS','3H']) puts [hand1, hand2].sort.last.score

    results in hand2 winning when in fact hand1 is the winner…

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>