gpt4 book ai didi

ruby - `String#===` 文档示例

转载 作者:数据小太阳 更新时间:2023-10-29 08:37:26 26 4
gpt4 key购买 nike

字符串类文档 (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

我预计这应该返回 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后代 . Ruby 中的任何类默认继承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.

根据上述原则 - As 'some_txt' String 的实例和 fooFoo 的实例, 'some_txt' === foo (实际上是 foo == 'some_txt' ,因为 Object#=== 将调用委托(delegate)给 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

关于ruby - `String#===` 文档示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28020807/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com