In continuation of another question I also have the following question.
I have a class which has a very central instance variable called var
. It is so central to the class that when I print an object of the class, it should just print the instance variable.
When I compare that same object with a string which matches the instance variable, I would like it to return true, but that doesn't always work in the implementation below:
class MyClass
attr_accessor :var
def initialize(v)
@var = v
end
def to_s
@var.to_s
end
def inspect
@var.inspect
end
def ==(other)
self.var == other
end
# ... methods to manipulate @var
end
str = "test"
obj = MyClass.new("test")
puts obj # prints the var string - great this is what i want
p obj # prints the var string - great this is what i want
puts obj==str # returns true - great this
puts str==obj # returns false - oops! Fails since i didn't overload the == operator in String class. What to do? I don't think i want to "monkey patch" the String class.
I understand that it's not my overwritten == operator which is used. It's the one in the String class. What do you suggest I do to get around this? Am I going down the wrong path?
I read through the question What's the difference between equal?, eql?, ===, and ==? without getting an answer to my question.
CodePudding user response:
I understand that it's not my overwritten == operator which is used. It's the one in the String class. What do you suggest I do to get around this? Am I going down the wrong path?
Before trying anything else, have a look at the docs for String#==
:
If object is not an instance of
String
but responds toto_str
, then the two strings are compared usingobject.==
.
In other words: you have to implement to_str
and return the object's string value:
class MyClass
# ...
def to_str
@var.to_s
end
end
You can also return to_s
or use alias to_str to_s
.
With any of the above, you'd get:
"test" == MyClass.new("test")
#=> true
Note that to_str
should only be implemented by objects that are string-like.