3

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.

1
  • 8
    there is no "rails way" for that, "ruby way" maybe. Commented Jul 11, 2012 at 7:55

3 Answers 3

7

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 }
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.