0

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!!

Edited by arupface

3
Contributors
4
Replies
12
Views
4 Years
Discussion Span
Last Post by Taywin
0

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]

Edited by Taywin

0

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

0

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.

Edited by Taywin

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.