什么是“其他”对象,它是如何工作的?

Dlu*_*uks 1 ruby

other在类比较中经常看到使用,例如

def ==(other)
  ...
end
Run Code Online (Sandbox Code Playgroud)

或者

def eql?(other)
  self == other
end
Run Code Online (Sandbox Code Playgroud)

但我仍然没有找到它究竟是什么的解释。这里发生了什么?

也许这是另一个问题,但是开始一个方法==意味着什么?

Von*_*onD 6

在 ruby​​ 中,操作符实际上是方法调用。如果您有两个变量a并且b想要检查它们的相等性,您通常会写a == b,但您可以写a.==(b). 最后一个语法显示了在相等性检查期间会发生什么:ruby 调用a的方法==并将其b作为参数传递。

您可以通过定义==和/或eql?方法在您的类中实现自定义相等性检查。在您的示例中,other只是它接收的参数的名称。

class Person
     attr_accessor :name

    def initialize name
        @name = name
    end
end

a = Person.new("John")
b = Person.new("John")
a == b # --> false

class Person
    def == other
        name == other.name
    end
end
a == b # --> true
Run Code Online (Sandbox Code Playgroud)

对于您的第二个问题,唯一==允许以您开头的方法是==and ===。在此处查看 ruby​​ 中方法名称限制的完整列表:Ruby 中方法名称的限制是什么?