Defining to_s
on a class works as I expect:
class Foo
def to_s
"Joe"
end
end
f = Foo.new
"hello #{f}" # => "hello Joe"
I attempt to utilize to_i
and expect it to work in a similar fashion. I expect that, by defining to_i
to be a number, then anywhere a number is expected, the object will return that number in the place of the object; in a situation like the following, I expect it to return the integer 5
. Instead, it raises an error:
class Foo
def to_i
0
end
end
f = Foo.new
5 + f # => TypeError: Foo can't be coerced into Fixnum
What does defining to_i
enable? How do you utilize it? Can I implicitly represent this object as an integer and return 0
just like the object implicitly returns the string "Joe"
?