Introduction
Ruby is a general-purpose, dynamic, reflective, object-oriented programming language. Everything in Ruby is an object, except blocks, which have replacements in the form of procs and lambda. Ruby's development aimed to create a useful interface between human programmers and the underlying computational machinery.
Ruby's syntax is comparable to that of many other programming languages, such as C and Java, making learning simple for Java and C programmers. It works on a wide range of platforms, including Windows, Mac OS X, and Linux.
Let’s discuss about the object ordering in Ruby, what ordering is, and how it is done in Ruby.
What is Ordering?
Ordering: For any two instances of a class in ruby, the two instances must be equal, or one instance must be less than the other.
In Ruby, classes define an ordering by implementing the <=> operator.
The most obvious classes for which such an ordering is defined are Numbers. Strings are also sorted numerically according to the character codes that comprise the strings. (This is an approximate case-sensitive alphabetical order with the ASCII text.)
Class instances can be compared and sorted if the class defines an ordering.
Properties of <=> Operator
The main properties of <=> operator are:-
1.) Classes define ordering in Ruby by implementing the <=> operator.
2.) If the left operand is smaller than the right operand, this operator should return -1.
3.) If the two operands are equal, this operator should return 0.
4.) If the left operand is greater than the right operand, this operator should return 1.
5.) And, if the two operands cannot be adequately compared (for example, if the right operand belongs to a different class), the operator should return nil.
Examples
1.) 15 <=> 20 # it will return -1 since 15 is less than 20.
2.) 25 <=> 25 # it will return 0 since 25 is equal to 25.
3.) 50 <=> 25 # it will return 1 since 50 is greater than 25.
4.) "10" <=> 15 # it will return nil since integers and strings are not comparable.