Array comparison.. why does this work.

J

Jean Nibee

How does Ruby do Array comparision?

Code:
old_inventory = [ 'a', 'b', 'd' ]
new_inventory = [ 'a','e', 'c' ]

puts "The following files have been added: "
puts new_inventory - old_inventory
puts ""
puts "The following files have been deleted: "
puts old_inventory - new_inventory

Notice the output is correct so it's not a case of element 0's being
compared in each array.

So...

Does Ruby sort arrays in memory first? or is a scan done 1 element at a
time?

Thanks.
 
D

dblack

Hi --

How does Ruby do Array comparision?

One element at a time.
Code:
old_inventory = [ 'a', 'b', 'd' ]
new_inventory = [ 'a','e', 'c' ]

puts "The following files have been added: "
puts new_inventory - old_inventory
puts ""
puts "The following files have been deleted: "
puts old_inventory - new_inventory

Notice the output is correct so it's not a case of element 0's being
compared in each array.

So...

Does Ruby sort arrays in memory first? or is a scan done 1 element at a
time?

You're not doing comparison, though; you're doing subtraction.
Subtraction doesn't depend on order. You can think of it as
"without":

[1,2,3] - [1] => [2,3] # [1,2,3] without 1
[1,2,3,1] - [1] => [2,3] # [1,2,3,1] without 1
[1,2,3] - [2] => [1,3] # [1,2,3] without 2

etc.


David

--
Q. What is THE Ruby book for Rails developers?
A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black)
(See what readers are saying! http://www.rubypal.com/r4rrevs.pdf)
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (http://www.rubypal.com)
 
J

Jean Nibee

You're not doing comparison, though; you're doing subtraction.
Subtraction doesn't depend on order. You can think of it as
"without":

[1,2,3] - [1] => [2,3] # [1,2,3] without 1
[1,2,3,1] - [1] => [2,3] # [1,2,3,1] without 1
[1,2,3] - [2] => [1,3] # [1,2,3] without 2

etc.


David

Sorry, when I mentioned comparison I meant "Under the hood". (I realise
'-' is subtractions ), but the interpreter needs to perform comparisoin
to see if an element exists somewhere.

I was curious if it just interates through one array looking for that
element in the second, or does it (internally) sort the array, iterate
each array performing comparision and if a > b skipping the equality
determination to save CPU cycles and doing a 'next'.

I guess what I"m saying (Makes more sense when you see pseudo code) is
how does it work in the interpreter.
 

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
474,236
Messages
2,571,183
Members
47,818
Latest member
KazukoXea6

Latest Threads

Top