Ruby"等于"

时间:2020-03-05 18:45:20  来源:igfitidea点击:

是否有与Python的" is"相当的Ruby?它测试两个对象是否相同(即具有相同的存储位置)。

解决方案

回答

使用a.equal? b

http://www.ruby-doc.org/core/classes/Object.html

Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b).

回答

我们也可以使用__id__。这为我们提供了对象的内部ID号,该ID号始终是唯一的。要检查对象是否相同,请尝试

a.__id__ = b.__id__

据我所知,这就是Ruby的标准库的工作方式(请参阅group_by和其他内容)。