Just a quick reference post.
There are several pairs of type coercions methods in Ruby:
What’s the difference and when to use/implement each of pair?
Shorter version is explicit conversion:
- your type should implement if it can be somehow converted into target type (integer, string, array and so on);
- you should call those method on incoming data, if you expect it to have some means of converting to target type.
Longer version is implicit conversion:
- your type should implement it only if it sees itself as “kind of” target type (“better” or “specialized” number, string, array, hash);
- you should call those methods on incoming data, if you have strict requirement for it being of target type, but want to check it in Ruby way, with duck typing, not class comparison;
- you should not implement and use this methods in other cases!
Most of Ruby operators and core methods use implicit conversions on data:
"string" + otherwill call
[1,2,3] + otherwill call
#to_aryand so on (and will raise
TypeError: no implicit conversionif object not responds to this methods);
"string" * otherand
[1,2,3] * otherwill call
a, b, c = *otherwill call
other#to_ary(and, therefore, can be used to “unpack” custom collection objects—but also can cause unintended behavior, if
to_arybut was not thought as a collection);
some_method(*other)—same as above, uses
some_method(**other)—new in Ruby 2, uses
I should repeat: never implement implicit conversion methods unless
you sure know what you are doing! It is widely seen, for example, the
#to_hash method being implemented (maybe because of “prettier name”
#to_h?) and causing strangest effects.