Sebastian Hungerecker
9/14/2008 11:30:00 AM
Adam Akhtar wrote:
> class thing
> attr_accessor :name :job
> end
Thing = Struct.new(:name, :job)
> and i want to ensure that if i have an array of these objects there will
> be no duplicates. A duplicate would be where both the name and job are
> the same in both objects.
>
> I tried using uniq! but it didnt work. Not sure why (can someone explain
> that).
For uniq to work your class has to implement hash and eql?, so that for any
two objects that you consider equal o1.hash == o2.hash and o1.eql?(o2) and
for any two objects that you do not consider equal !o1.eql?(o2) (o1.hash may
still be equal to o2.hash, but should not be).
> Ive heard of set, could that be used in this case to prevent duplicates
> being added?
If uniq does not work, set does not work either. Once you implement hash and
eql?, yes, set can be used.
If you use Struct to define your class, like I demonstrated above hash and
eql? will be defined automatically. If you can't use a struct, you could
define them as such:
class Thing
attr_accessor :name, :job
def hash
[name, job].hash
end
def eql?(other)
[name, job].eql?([other.name, other.job])
end
end
HTH,
Sebastian
--
NP: Die Apokalyptischen Reiter - Heut' Ist Der Tag
Jabber: sepp2k@jabber.org
ICQ: 205544826