If I have a custom Ruby class representing some string type, as in
class MyString
end
Which functions should I implement in order to make the following use cases possible:
- Passing a Ruby string whenever a
MyStringis expected - Passing a
MyStringwhenever a Ruby string is expected - Comparing a Ruby string with a
MyStringvalue (it shouldn’t matter whether I uses == tort == s).
I saw various interesting functions like to_s, cmp, == and eq already, but it’s not clear to me when each of them is called.
My concrete use case is that I’m writing a Ruby extension using the C API which exposes functions taking (and returning) values of a custom string type (QString, to be precise) which my extension also registers. However, I’d like to make those custom strings behave as intuitive as possible. Unfortunately I can’t just return Ruby strings from my C code since it should be possible to call Qt methods on the strings.
There are at least three approaches:
class MyString < String; ...; end#to_s#to_strDoing both #2 and #3 will make the object act very much like a real String even if it isn’t a subclass.
#to_sis an explicit converter, meaning it must appear in Ruby code to work.#to_stris an implicit converter, meaning the Ruby interpreter will attempt to call it when it wants a String but is given something else.Update:
Here is an example of some fun you can have with
to_str:When run, the first open fails with
TypeErrorbut the second proceeds to looking for1.