gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:54:45 25 4
gpt4 key购买 nike

docs对于 Array#include? 指定使用 == 运算符检查包含。我在使用自定义 == 将对象与自身进行比较的情况下进行检查:

class Foo
def ==(other)
false
end
end

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

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

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

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

最佳答案

阅读源码

               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) 比较指针并返回 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

关于ruby - 使用#include 将对象与自身进行比较时不使用自定义 == 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54362241/

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