array equality question

C

Chris McMahon

This took me by surprise:

irb(main):001:0> a1 = ['x','y','z']
=> ["x", "y", "z"]
irb(main):002:0> a2 = ['y','z','x']
=> ["y", "z", "x"]

irb(main):008:0> puts "yo" if a1 == a2
=> nil
irb(main):009:0> puts "yo" if a1 != a2
yo
=> nil

I assumed order of elements would not be considered for equality. Is
there any particular reason for this behavior?
 
R

Robert Klemme

This took me by surprise:

irb(main):001:0> a1 = ['x','y','z']
=> ["x", "y", "z"]
irb(main):002:0> a2 = ['y','z','x']
=> ["y", "z", "x"]

irb(main):008:0> puts "yo" if a1 == a2
=> nil
irb(main):009:0> puts "yo" if a1 != a2
yo
=> nil

I assumed order of elements would not be considered for equality. Is
there any particular reason for this behavior?

Why should order not matter? An array is an *ordered* list of elements
as indexing by position indicates. a1[0] == a2[0] will return false,
why then should a1 == a2 return true?

If you to ignore order you either have to compare sorted copies or
resort to Set.

Kind regards

robert
 
W

William James

Chris said:
This took me by surprise:

irb(main):001:0> a1 = ['x','y','z']
=> ["x", "y", "z"]
irb(main):002:0> a2 = ['y','z','x']
=> ["y", "z", "x"]

irb(main):008:0> puts "yo" if a1 == a2
=> nil
irb(main):009:0> puts "yo" if a1 != a2
yo
=> nil

I assumed order of elements would not be considered for equality. Is
there any particular reason for this behavior?

The reason for this behavior is that the creator of Ruby
and most of its users aren't devoid of knowledge of
programming. An array is not a set. An array is not a
hash (a.k.a. associative array). So of course order matters.
Does the order in which you read the chapters of a novel
matter? If order doesn't matter, then why is there a 'sort'
method that changes the order of an array?
 
G

gwtmp01

I assumed order of elements would not be considered for equality. Is
there any particular reason for this behavior?

The concept of order is an integral part of what it means to be an
Array.
If you aren't interested in order, then a Set is probably a better
structure.

require 'set'

a = [1,2,3]
b = a.reverse
p a == b # false
p Set.new(a) == Set.new(b) # true

Gary Wright
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,772
Messages
2,569,593
Members
45,111
Latest member
VetaMcRae
Top