Posted over 5 years ago. Visible to the public. Repeats. Linked content.

About Ruby's conversion method pairs

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:

args = [1,2,3] 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

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.

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Dominik Schöler
Last edit:
over 3 years ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Dominik Schöler to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more