Parsing Measurements in Ruby

About two weeks ago, I released a new Ruby gem into the wild named ruby-measurement. (Unfortunately, measurement was already taken.) It serves as a means of parsing human-readable text into a quantity and unit, which can then be used for converting among units and other mathematical operations.

Let’s take a simple string like “4 1/2 dozen”. With it, we can do the following:

Okay, now this is starting to look a little more useful. But how did the convert_to call know how to convert between those units? Easy enough, unit definitions include not only the name (and aliases), but also conversion definitions for casting from one measurement to another. Here’s an example of how “feet” and “inches” are implemented (truncated for simplicity).

By default, ruby-measurement ships with a variety of predefined areas, lengths, volumes, weights & capacities for both metric and U.S. customary units. With the power of the Measurement.define call, you can define any type of unit and conversion you want.

If that’s not cool enough, how about automatically casting between units when performing operations on them?

As long as a unit define a conversion rule for casting to another unit, mathematical operation will automatically cast to the former measurement’s unit. In the above example, the kilograms object was the first measurement provided in the operation, which is why the unit chosen to perform the operation was kilograms.