`String#===` 文档示例

`String#===` documentation example

字符串 class 文档 (2.1.1) 将 === 运算符描述为:

If obj is not an instance of String but responds to to_str, then the two strings are compared using case equality Object#===.

我在一个例子中试过这个,但它不起作用。这是我的尝试方式:

class Foo
  def to_str
    'some_txt'
  end
end

foo = Foo.new
'some_txt' === foo #=> false

我预计这应该 return true。但事实并非如此。我问是否有人可以在示例中显示此描述。我在这里做错了什么?

If obj is not an instance of String but responds to to_str, then the two strings are compared using case equality Object#===.

在你的例子中 foo 响应 #to_str,但不是 String 的实例。所以 'some_txt' === foo 实际上是在使用 Object#===

Case Equality – For class Object, effectively the same as calling #==, but typically overridden by descendants to provide meaningful semantics in case statements.

FooObject 后代 class。 Ruby 中的任何 class 默认情况下 Object 继承 。现在 Foo 没有覆盖方法 #===,因此根据文档,它将使用 Object#== 方法。 Object#== 的文档说:

Equality — At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendant classes to provide class-specific meaning.

根据上述原则 - 由于'some_txt'String的实例,而fooFoo的实例, 'some_txt' === foo(实际上是 foo == 'some_txt',因为 Object#=== 将调用委托给 Object#==)给出 false.

Object#==Object#=== 的文档都说 -

Typically, this method is overridden in descendant classes to provide class-specific meaning.

这意味着您可以覆盖 Object#===Object#== 来实现您的比较逻辑。只是为了模拟我刚才所说的,我放了一个虚拟示例代码:-

class Foo
  def to_str
    'some_txt'
  end

  def ==(other)
    true
  end
end

foo = Foo.new
'some_txt' === foo # => true
foo.class.superclass # => Object