Stuff about software development, agile and testing

Sunday, August 26, 2007

Five different ways to test equality

It's bit confusing when it comes to test equality of objects in Ruby. It has five different ways to do it and each one has a different purpose and context in which it should be used.

equal? returns true if receiver and the parameter object have same object_id. Object ids are unique and its not shared among the objects. This method should not be overridden

== returns true if the receiver and parameter object has same values. This is most intuitive and should be overridden in your sub-classes

eq? Like == it compares objects but is more strict about type. Only reason this exists is to compare Hash keys

=== This is used for Switch Case statement. It compares target in case statement with each selectors. You can override it to control the way case statements are matched inside the switch block

=~ Pattern matching (Side note: In Erlang = does the pattern matching)

== and =~ does have a negated version and since ruby is a great language if you implement == you != for free, isn't that great.

Next time when you have to equate objects you know which one to use