I want to know what is the meaning of def <=>(other) in ruby methods. I want to know what is the <=> in ruby method.
Asked
Active
Viewed 95 times
3
Boris Stitnicky
- 12,093
- 5
- 54
- 73
3 Answers
2
<=> is not "in" Ruby method, #<=> is a Ruby method. This method is used for comparable objects (members of ordered sets) to easily gain implementation of #<, #>, #== etc. methods by including Comparable mixin.
class GradeInFiveLevelScale
include Comparable
attr_reader :grade
def initialize grade; @grade = grade end
def <=> other; other.grade <=> grade end
def to_s; grade.to_s end
end
a = GradeInFiveLevelScale.new 1
b = GradeInFiveLevelScale.new 1
c = GradeInFiveLevelScale.new 3
a > b #=> false
a >= b #=> true
a > c #=> true
Boris Stitnicky
- 12,093
- 5
- 54
- 73
2
Read this Equality, Comparison and Uniqueness in Ruby. Nice blog it is.
Arup Rakshit
- 113,563
- 27
- 250
- 306
-
And here is a skinny of it: Apart from three-way comparison `#<=>`, another odd method you need to know of is triple equals `#===`, which is immensely important in `case` statements, and less so in `rescue` statements. Also check `#eql` and `#equal` methods. – Boris Stitnicky May 17 '13 at 09:57
-
@BorisStitnicky `#=== is less important in rescue statements.`. Not understood. Can you tell me more or point me to any docs for this. I was unaware of the use `===` in rescue. – Arup Rakshit May 17 '13 at 10:02
-
1One of the things you have to do if you want to be good in Ruby, is to read books, something that I don't do often anymore. One of such books to recommend is _Exceptional Ruby_ by Avdi Grimm. I have not read that book, but I want it in my bookshelf. I learned about the way the exceptions are matched to each other in `rescue` statement from Avdi's somewhat tedious talk: http://www.confreaks.com/videos/523-roa2011-exceptional-ruby – Boris Stitnicky May 17 '13 at 10:11
-
@BorisStitnicky Humm.. That I read that book awesome it is. But forgot some tips. :P – Arup Rakshit May 17 '13 at 10:20
-
The part in question starts at 8:45 of the talk. – Boris Stitnicky May 17 '13 at 10:28