About Ruby's conversion method pairs

Updated . Posted . Visible to the public. Repeats.

Ruby has a set of methods to convert an object to another representation. Most of them come in explicit and implicit flavor.

explicit implicit
to_a to_ary
to_h to_hash
to_s to_str
to_i to_int

There may be even more.

Don't name your methods like the implicit version (most prominently to_hash) but the like the explicit one.

Explicit conversion

Explicit conversion happens when requesting it, e.g. with the splat operator:

args = [1,2,3]
some_method(*args) # Ruby calls args.to_a here

Implicit conversion

Implicit conversion happens when Ruby tries to convert an object when it thinks it should:

a, b, c = args # Ruby calls args.to_ary here

# Fictional example; Ruby decomposes the block argument by calling args.to_ary
[args].each do |(x, y, z)| puts x, y, z; end

Important

You should only implement an implicit conversion method if your object already behaves like the target type.
You never create a new object in an implicit conversion method. This method should either return self or not be implemented at all.

Obviously, this is the reason behind this recent card about Ruby implicitly converting a hash to keyword arguments. It's not a bug, it's a feature!


Also see the linked Stackoverflow post.

Dominik Schöler
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2015-10-20 11:14)