使用#include 将对象与自身进行比较时不使用自定义 == 运算符?

Custom == operator not used when comparing an object with itself with #include?

Array#include?docs 指定使用 == 运算符检查包含。我在使用自定义 ==:

将对象与自身进行比较的情况下进行检查
class Foo
  def ==(other)
    false
  end
end

f = Foo.new
f == f # => false 

在这种情况下,文档的描述不是这样的,另一种机制优先:

[f].include?(f) # => true

这个机制是什么,在哪里定义的?

我刚刚查看了源代码:https://apidock.com/ruby/Array/include%3F

我相信 ruby 使用默认运算符 (rb_equal) 而不是此函数的对象运算符。

阅读源代码

               VALUE
rb_ary_includes(VALUE ary, VALUE item)
{
    long i;
    VALUE e;

    for (i=0; i<RARRAY_LEN(ary); i++) {
        e = RARRAY_AREF(ary, i);
        switch (rb_equal_opt(e, item)) {
          case Qundef:
            if (rb_equal(e, item)) return Qtrue;
            break;
          case Qtrue:
            return Qtrue;
        }
    }
    return Qfalse;
}

https://ruby-doc.org/core-2.2.0/Array.html#method-i-include-3F 你会看到 ruby 没有使用你的对象运算符

编辑:如 aleksei-matiushkin 所述(在评论中),rb_equal_opt(e, item) 比较指针和 returns true

反转它,你可以用:

class Foo
  def ==(other)
    puts "yay"
    true
  end
end

> f = Foo.new
=> #<Foo:0x0000000001048610> 
> [f].include?(f)
=> true 
> [f].include?(f.dup)
yay
=> true