From: Marcin Wolski Date: 2010-06-04T10:41:29+09:00 Subject: Re: comparing objects Anderson Leite wrote: > How can I compare two objects and get true if some of his atributes are > equals ? > > I need to compare two arrays of users, and get and third array just with > the matches. I found the "&" method that work for Fixnuns and String, > but...how to use with objects ? > > > class User > attr_accessor :email > end > > a = User.new > a.email = 'ruby@rails.com' > > b = User.new > b.email = 'ruby@rails.com' > > array_one = [a] > array_two = [b] > > > array_three = array_one & array_two > > puts array_three # I want the user here > > > > Can you help me ? > thanks I think you need to define how to compare your objects and their hash. Have a look below. class User attr_accessor :email def ==(other) @email == other.email end alias eql? == def hash code = 17 code = 37*code + @email.hash end def to_s "#@email" end end a = User.new a.email = 'ruby@rails.com' c = User.new c.email = 'groovy@rails.com' b = User.new b.email = 'ruby@rails.com' d = User.new d.email = 'c++@rails.com' d = User.new d.email = 'python@rails.com' array_one = [a,d] array_two = [b, c] array_three = array_one & array_two puts array_three # I want the user here #prints ruby@rails.com -- Posted via http://www.ruby-forum.com/.