Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 323
Rahul Tapali Avatar asked Sep 10 '26 07:09

Rahul Tapali


2 Answers

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 }
like image 129
tokland Avatar answered Sep 12 '26 22:09

tokland


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.

like image 20
Salil Avatar answered Sep 12 '26 22:09

Salil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!