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.
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 }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With