Forum: Ruby on Rails Arrays of Model Objects, Intersections, Object Identificatio

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
09ff21c336ae126e8b3199f8b64d7796?d=identicon&s=25 D. Taylor Singletary (Guest)
on 2006-03-16 23:47
(Received via mailing list)
Hi all,

Hope you can help me with understanding how Ruby / Rails treats arrays
of objects.

Let's say I have to arrays of objects. Both are the same kinds of

tomatoes = Fruit.find(:all, :conditions => [ 'tomato = ?', true], :limit
fruits = Fruit.find(:all, :limit => 10)

And I want to create an array of these objects called @my_fruits, but I
don't want the set to contain any duplicates.

In the Ruby API documentation for arrays it shows you can use the |
to perform a union between two arrays, throwing out duplicates.

OK. That sounds good. That's what I want.

@my_fruits = tomatoes | fruits

98% of the time I've found this works in my tests. I don't get
But I've had instances where I do in fact have a row repeat.

Any ideas as to why the union operator doesn't work in this case?

In my real world (tm) example, I'm sorting the database rows randomly,
the data changes frequently. Both arrays contain the same types of
In entirely likely that two arrays can contain the same object.

Is there a performance hit in building an each loop on the likely
smaller of
the array to test whether the other array ".include?"s the object? Would
this be considered more reliable?

@my_fruits = fruits
tomatoes.each do | fruit |
  @my_fruits.push(fruit) unless @my_fruits.include?(fruit)


D. Taylor Singletary,
Reality Technician
9d1f5d2d9de70bd9a934f557dc95a406?d=identicon&s=25 Daniel ----- (liquid)
on 2006-03-16 23:59
(Received via mailing list)

Have you tried the uniq! method for arrays? (ruby 1.84)

Something like


Hope this works for you
09ff21c336ae126e8b3199f8b64d7796?d=identicon&s=25 D. Taylor Singletary (Guest)
on 2006-03-20 16:35
(Received via mailing list)
I figured this out in a duh moment this morning. One array was formed
through traditional ActiveRecord find methods and the other was
with a find_by_sql string that included a join table in the select. The
inclusion of the join table made the objects appear as different between
two sets. Sanity reset.

Thanks for the suggestions.

D. Taylor Singletary,
Reality Technician
This topic is locked and can not be replied to.