A Ruby Conversion Idiom

@CapnKernul writes:

[do you know of] a Ruby idiom for converting an object to a type if it isn’t already that type. For example, if you want to only store an attribute of type Foo, you could write an accessor method that would pass any non-Foo object to Foo’s constructor.

There is a de facto idiom among Ruby built-ins to define a method with the same name as a class for doing conversions to that class. My favorite is Kernel#Array:

But there are others. Kernel#Integer provides a stricter form of integer conversion than does #to_i:

And there are also Kernel#String, Kernel#Float, Kernel#Complex, and Kernel#Rational:

You can also find this in standard libraries. The URI library defines an idempotent conversion method for URIs:

There’s also Pathname:

I like to extend this idiom into my own code for idempotent conversions into commonly-used value objects. I did this in Objects on Rails for TagList objects.

The TagList method is shorter than calling TagList.new(...). And in addition, it’s safe to call on inputs which might or might not already be TagList objects. Although they may look a little odd at first, capitalized conversion methods are a well-established Ruby idiom for methods which “do the right thing” to convery any reasonable input value into a desired class. And because unlike #to_x methods they are outside of the objects being converted, they incur none of the maintenance danger of a monkey-patch. I don’t define them for every class in my program; but for oft-used value object types they can be quite convenient.