The comparison operators:

  • ===

  • <=>

  • eql?

  • equal?

  • ==

Both are performing equality check I know. Some of them overrides == also. But now my query is how to think,what to use in what situations?

Explanation with a code would be better idea to understand.

Thanks in advance!!

For these operators (==, ===, eql?(), equal?()), you better read how OO programming works. It is similar to Java language (comparing object reference or object value).

The <=> operator is similar to compare() in Java. It returns -1 if the caller value is less than, 0 if equal, and 1 if greater than the argument value. It usually is used in sorting.

a = [1, 4, 8, 3, 6, 5]
b = a.sort {|x,y| x<=>y}  # ascending order
# now b is [1, 3, 4, 5, 6, 8]
b = a.sort {|x,y| y<=>x}  # descending order
# now b is [8, 6, 5, 4, 3, 1]

output of b = a.sort is same as b = a.sort {|x,y| x<=>y}. Then why you used <=> operator. Couldn't get your point. Can you clarify it please? - to show what you used the spaceship operator?

Thanks

The code block which comes after the .sort is a customized inline version of whatever you want to do with the sort. The example is simply a Fixnum array which has its default behavior for sorting.

If you are going to sort an object, you will need to implement your own sort.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.