Peter Harkins at Push.cx wrote a bit of code in python. I’ve noticed Python and Ruby being very similar, so I wanted to rewrite his example code in Ruby and see how it compares. His motivation was to basically find a way to compare two objects for equality (containing the same values for its members) since the == operator doesn’t function as expected.

Here’s my code:

values = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
suits = ['h', 'c', 'd', 's']

class Card

attr_reader :value, :suit
protected :value, :suit

def initialize(value, suit)
@value, @suit = value, suit
end

def to_str
sprintf “<card: %s, %s>”, @value, @suit
end

def equal( other )
(@value == other.value) && (@suit == other.suit)
end

end

This may not be the best implementation, I’m new to Ruby so there is probably a better way to do it! I created attribute readers and then set them as protected so only other instances of class “Card” can call it (don’t need public access right now, so why open that door?). Constructor takes the two parameters and sets the class variables. The method to_str . . . It was my impression that if I defined a to_str method and did “puts card” it would automagically call the to_str object.. but no, it didn’t work. Ok then what is the advantage over defining to_s?

When I run it

card1 = Card.new(”3″, “s”)
puts card1.to_str
# prints <card: 3,s>

card2 = Card.new(”3″, “s”)
puts card2.to_str
# prints <card: 3,s>
puts “is card 1 the same as card 2?”
puts card1 == card2

# result would be:
# is card 1 the same as card 2?
# false

puts “now using equal method”
puts card1.equal(card2)

# result would be:
# now using equal method
# true

BTW - printing the instance var itself renders something goofy like:
#<card:0×2815b38>

It’s the object id, which is why you can’t use the == operator, since each id is different