Nikita  Luparev Nikita Luparev - 1 year ago 30
Ruby Question

What methods gets called when I try to compare custom object with string?

I have some object that I'd like to compare with string. I'd like to know what method should I implement in order conversion of my object happens automatically when used as an argument to comparison operator.

For example:

line == '2 hello world'

at the left my object and I'd like to compare it with some string. Currently, I've implemented to_s on my object, but nevertheless I get false even if contained string is equal to which I'm comparing with.

Thanks in advance.


You need to override your class' == method.

class MyClass
  def ==(other)
    # custom equal comparison logic here
    # if you just need string comparison
    to_s == other