覆盖 Ruby 中的 == 运算符 [英] Overriding the == operator in Ruby

查看:70
本文介绍了覆盖 Ruby 中的 == 运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据文档Array.include? 在对象上使用 == 比较.我来自 Java,在那里这些事情(通常)是用 .equals() 完成的,它很容易为特定对象覆盖.

According to the docs, Array.include? uses the == comparison on objects. I come from Java where such things are (usually) done with .equals() which is easy to override for a particular object.

如何在 Ruby 中覆盖 == 以允许我为我的特定对象指定 Array.include? 的行为?

How can I override == in Ruby to allow me to specify the behaviour of Array.include? for my particular object?

推荐答案

在 Ruby 中 == 只是一个方法(上面有一些语法糖,允许你编写 foo == bar 而不是 foo.==(bar)) 并且您覆盖 == 就像您使用任何其他方法一样:

In Ruby == is just a method (with some syntax sugar on top allowing you to write foo == bar instead of foo.==(bar)) and you override == just like you would any other method:

class MyClass
  def ==(other_object)
    # return true if self is equal to other_object, false otherwise
  end
end

这篇关于覆盖 Ruby 中的 == 运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆