1

What would be the most the concise way to express the following in Ruby:

Is x more, less or equal to the value y?

Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232

1 Answers1

5

Do as below using spaceship operator(<=>) :

Returns 0 if obj and other are the same object or obj == other, otherwise nil.

The <=> is used by various methods to compare objects, for example Enumerable#sort, Enumerable#max etc.

Your implementation of <=> should return one of the following values: -1, 0, 1 or nil. -1 means self is smaller than other. 0 means self is equal to other. 1 means self is bigger than other. Nil means the two values could not be compared.

x <=> y
Community
  • 1
  • 1
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
  • 1
    Beat me to it :) Check this out too: http://stackoverflow.com/questions/827649/what-is-the-ruby-spaceship-operator – ygoncho Jan 21 '14 at 14:42
  • 1
    It will return `-1` if x is less than y, `0` if they are equal and `1` if x is larger than y. – Agis Jan 21 '14 at 14:49