From: Robert Klemme Date: 2010-06-05T21:35:10+09:00 Subject: Re: comparing objects On 05.06.2010 00:35, Anderson Leite wrote: > Before >> we can provide solutions we have to know what problem must be solved. > I have a list of objects that came from database and another list of > objects extracted from a xml. I need the elements who are in both lists. > > > Then...I thought to compare objects overriding the == method like Marcin > Wolski wrote. There is another solution ? If all objects you are dealing with implement #eql? and #hash in a way to be suitable for that comparison then using #eql? is the most straightforward approach. If they do not and you want to do the comparison based on other criteria then you need to pick a different solution. For example: in_both = obj_from_db.select do |u1| obj_from_xml.any? do |u2| u1.email == u2.email && u1.age == u2.age end end The larger set should be used for the outer iteration. If both sets are really large then you probably rather want to use a different strategy by speeding up access via a Hash. For that you need a specific Hash key (remember, we had assumed #eql? and #hash cannot be used). That key must implement #eql? and #hash; the easiest way to get such a Key class is to use Struct: Key = Struct.new :email, :age db_index = {} obj_from_db.each do |u1| db_index[Key[u1.email, u1.age]] = u1 end in_both = obj_from_xml.select do |u2| db_index[Key[u2.email, u2.age]] end Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/