From: Tim Hunter Date: 2006-08-01T21:30:10+09:00 Subject: Re: check if 2 objects are equal N Okia wrote: > If you want to define equivalence for your classes, you really need to > do so yourself. > > The easiest way is to make the class Comparable, and define your own > <=> operator. You can be as simple or as complex as you like: > > class MyClass > include Comparable > > attr_accessor :my_age, :my_first_name, :my_last_name > > def initialize(age,first_name,last_name) > @my_age = age.to_i > @my_first_name = first_name > @my_last_name = last_name > end > > def <=>(other) > # if the other class being compared is nil, we aren't equivalent > return nil if other.nil? > > # Simple case, if both objects have same objectid, they are the same > return 0 if object_id == other.object_id > > # Define a heirarchy of tests for this class > if (@my_age == other.my_age) > if (@my_first_name <=> other.my_first_name) == 0 > return @my_last_name <=> other.my_last_name > else > return @my_first_name <=> other.my_first_name > end > else > return @my_age <=> other.my_age > end > end > > end > The simplest way to do this is: def <=>(other) return [@my_age, @my_first_name, @my_last_name] <=> [other.age, other.my_first_name, other.my_last_name] end