3

我想知道def <=>(other)ruby​​ 方法中的含义是什么。我想知道<=>红宝石方法是什么。

4

3 回答 3

2

<=>不是“入”Ruby 方法,#<=>是一种Ruby 方法。此方法用于可比较对象(有序集合的成员) ,以通过包含mixin轻松实现#<、等方法。#>#==Comparable

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
于 2013-05-17T09:46:38.827 回答
2

<=> 是组合比较运算符。如果第一个操作数等于第二个,则返回 0,如果第一个操作数大于第二个,则返回 1,如果第一个操作数小于第二个,则返回 -1。

有关此SO 线程的更多信息。

于 2013-05-17T09:46:52.833 回答
2

读这个Equality, Comparison and Uniqueness in Ruby。不错的博客。

于 2013-05-17T09:47:44.973 回答