1

Have following example of code:

%w{ Ruby C APL Perl Smalltalk}.min {|a,b| a.size <=> b.size}  

return "C"

Can you explain me why "C"? What makes an operator "<=>" ?

Stefan Hansch
  • 1,550
  • 4
  • 22
  • 55

1 Answers1

1

The Spaceship operator returns -1 if the left is less than the right, 0 if they are equal, and 1 if the left is greater than the right.

In this case, you're comparing the length of each word in the array and returning the shortest word. If you removed .size from the variable in the block, it would instead return the first word that occurs alphabetically (i.e. 'APL').

What is the Ruby <=> (spaceship) operator?

Community
  • 1
  • 1
Scott Schupbach
  • 1,284
  • 9
  • 21