在Ruby中覆盖==运算符 [英] Override == operator in Ruby

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

问题描述

根据 docs 数组.包括?对对象使用 == 比较.我来自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天全站免登陆