Read more

About Ruby's conversion method pairs

Dominik Schöler
October 20, 2015Software engineer at makandra GmbH

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
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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
October 20, 2015Software engineer at makandra GmbH
Posted by Dominik Schöler to makandra dev (2015-10-20 13:14)