Different between 2 code

  • Thread starter Amir Ebrahimifard
  • Start date
A

Amir Ebrahimifard

Hi
Why 2 different sort in below code return different result ?
( I dont understand different between "v1 <=> v2" and "v2 <=> v1" ).

------------------------------------------
array = [3,1,5,2,4]
# => [3, 1, 5, 2, 4]

array.sort {|v1,v2| v1 <=> v2 }
# => [1, 2, 3, 4, 5]
array.sort {|v1,v2| v2 <=> v1 }
# => [5, 4, 3, 2, 1]
 
B

Bob Smith

( I dont understand different between "v1 <=> v2" and "v2 <=> v1" ).

I think a quick Google search on the "spaceship operator" should help
you with understanding the differences.
 
B

Brian Candler

Amir said:
Hi
Why 2 different sort in below code return different result ?
( I dont understand different between "v1 <=> v2" and "v2 <=> v1" ).

irb(main):001:0> 1 <=> 2
=> -1
irb(main):002:0> 2 <=> 1
=> 1
irb(main):003:0> 1 < 2
=> true
irb(main):004:0> 2 < 1
=> false
 

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,146
Messages
2,570,832
Members
47,374
Latest member
EmeliaBryc

Latest Threads

Top