Monday, February 27, 2012

Re: [Rails] Compare arrays

On Feb 27, 2012, at 6:05 PM, Bill Walton wrote:

> On Mon, Feb 27, 2012 at 4:51 PM, Rodrigo Ruiz <rodrigo.ruiz7@gmail.com> wrote:
>> 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

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate