Compare arrays

Hi, does anyone know how to compare to arrays not considering their order?

For example:

if I compare [1, 4, 2] with [4, 1, 2], this should return true.

Thanks in advance.

You can try this

[1,4,2].map{ |a| [4,1,2].include?(a)}

I managed to do this by hand.

I was actually looking for something already native to ruby.

ruby-1.9.2-p290 :004 > [4,1,2] == [1,4,2] => false ruby-1.9.2-p290 :005 > [4,1,2].sort == [1,4,2].sort => true

Like that?

Ya, that is what I used (with sort), I was just wondering if there is a native way like:

a = [1, 4, 2]

b = [2, 1, 4]

a.has_same_elements_as(b)

Although now I think sort is the best way.

Thank you all for replying.

Ya, that is what I used (with sort), I was just wondering if there is a native way like:

No need to waste cycles like that. Array math will do fine.

a = [1, 4, 2] b = [2, 1, 4]

a.has_same_elements_as(b)

ruby-1.9.2-p290 :001 > a = [4,1,2] => [4, 1, 2] ruby-1.9.2-p290 :002 > b = [1,2,4] => [1, 2, 4] ruby-1.9.2-p290 :003 > b - a => ruby-1.9.2-p290 :004 > a - b =>

HTH, Bill

Ya, that is what I used (with sort), I was just wondering if there is a native way like:

No need to waste cycles like that. Array math will do fine.

a = [1, 4, 2] b = [2, 1, 4]

a.has_same_elements_as(b)

ruby-1.9.2-p290 :001 > a = [4,1,2] => [4, 1, 2] ruby-1.9.2-p290 :002 > b = [1,2,4] => [1, 2, 4] ruby-1.9.2-p290 :003 > b - a => ruby-1.9.2-p290 :004 > a - b =>

HTH, Bill

You have to be careful if duplicated elements are important:

irb(main):001:0> a = [1,2,4] => [1, 2, 4] irb(main):002:0> b = [4,1,2] => [4, 1, 2] irb(main):003:0> c = [2,1,4,1] => [2, 1, 4, 1] irb(main):004:0> a == b => false irb(main):005:0> a.sort == b.sort => true irb(main):006:0> (a - b).empty? => true irb(main):007:0> (b - a).empty? => true irb(main):008:0> c == a => false irb(main):009:0> c.sort == a.sort => false irb(main):010:0> (c - a).empty? => true irb(main):011:0> (a - c).empty? => true

-Rob

Yes, duplicates are important.

Assuming nil entries may also be important...

ruby-1.9.2-p290 :016 > a = [2,1,4,nil,1] => [2, 1, 4, nil, 1] ruby-1.9.2-p290 :017 > b = [1,2,2,4,nil,nil] => [1, 2, 2, 4, nil, nil] ruby-1.9.2-p290 :018 > a.compact.uniq - b.compact.uniq => ruby-1.9.2-p290 :019 > a => [2, 1, 4, nil, 1] ruby-1.9.2-p290 :020 > b => [1, 2, 2, 4, nil, nil]

see Class: Array (Ruby 1.9.3) for other interesting Array methods.

HTH, Bill