2016-04-18 21 views
0

我有一些对象,我想比较字符串。我想知道我应该实现什么方法,以便在用作比较运算符的参数时自动发生对象转换。当我尝试将自定义对象与字符串进行比较时,会调用哪些方法?

例如:

line == '2 hello world' 

在离开我的目标,我想将它与一些字符串比较。目前,我已经在我的对象上实现了to_s,但即使包含的字符串与我正在比较的字符串相同,我也会得到错误。

在此先感谢。

+0

的可能的复制[什么是实现平等红宝石正确的方式(http://stackoverflow.com/questions/1931604/whats-the-right-way-to-implement-equality-in-ruby ) –

回答

2

您需要覆盖您的班级'== method

class MyClass 
    def ==(other) 
    # custom equal comparison logic here 
    # if you just need string comparison 
    to_s == other 
    end 
end 
相关问题