Rahul Tapali
Rahul Tapali

Reputation: 10137

Best way to compare two array of objects in rails

I have two array of objects for example:

a1 = [obj1, obj2 , obj3]
a2 = [obj4, obj5, obj6]

Each array has different objects of the same class. I want to check whether they have the same attribute value (obj1.att == obj4.att) in a single iteration.

a1.each will do iteration on a single array. I don't want to use for or while loop. I want a rails way to do that.

Upvotes: 3

Views: 5741

Answers (3)

tokland
tokland

Reputation: 67860

I guess it makes to sense to check that array sizes match before iterating:

same_att = a1.size == a2.size && a1.map(&:att) == a2.map(&:att)

Same idea, a lazy implementation (only if you have lots of elements in the arrays):

same_att = a1.size == a2.size && a1.lazy.zip(a2).all? { |x, y| x.att == y.att }

Upvotes: 7

Salil
Salil

Reputation: 47482

Try following

a1.map(&:att) == a2.map(&:att)

Edited Remember following thing

[1,2,3] == [1,2,3]  #true

AND

[1,2,3] == [2,3,1]  #false

Hence it will only returns true when att attribute of obj1, obj4 AND obj2, obj5 AND obj3, obj6 are same.

Upvotes: 4

AnkitG
AnkitG

Reputation: 6568

a1.each {|i| a2.sel­ect {|k|  k.att == i.att }}

Upvotes: 0

Related Questions