September 19, 2006
ruby-units
In scientific (and non-scientific) programming one frequently needs to be able to manipulate units such as ‘10 mm’, ‘6 gal’, or ‘3 weeks’. The traditional way to handle units in programming is to simply save the scalar part of the unit (i.e., the 10 from ‘10 mm’), and then make sure you programmatically convert the unit whenever necessary. Needless to say, this is error prone and it constrains the user to only being able to enter known unit types.
Ruby has a few libraries (notably, Facets) available that handle unit conversions in one form or another. However, most of these systems don’t quite meet my somewhat demanding and arbitrary requirements, so I set out to write a new one.
Installation
You can get ‘ruby-units’ using
Usage
To use this gem, you need to do the standard
-
require ‘rubygems’
-
require ‘ruby-units’
Creating a Unit object
Because I use a lot of units in my work, and I’m lazy, there are several different ways to create a new ‘Unit’ object.
- unit = Unit.new(”1 mm”)
- unit = Unit(”1 mm”)
- unit = U(”1 mm”)
- unit = “1 mm”.to_unit
- unit = “1 mm”.unit
- unit = “1 mm”.u
- unit = “mm”.unit (yields ‘1 mm’)
Of these, I use #5 the most since it is reasonably terse without becoming obscure.
You can also create Unit objects from Numerics, Arrays, and Time objects. Numerics just become unitless Unit objects, Arrays are interpreted as [scalar, numerator, denominator], and Time objects are converted into a number of seconds.
Unit objects can be serialized through YAML using ‘unit.to_yaml’, which facilitates them being stored in database columns using Rails’ :serialize functionality.
Unit strings generally consist of text in the following format:
-
R = "8.31451 kJ/mol*degK".unit
-
a = "9.8 m/s^2".unit
Since Units are constructed from strings, it is easy to have a user specify them in input fields. Because the format is fairly standard, there should not be too many problems with misinterpreted units.
A couple of points:
- only one ‘/’ per unit. No ‘m/s/s’
- everything after the ‘/’ is in the denominator
- you can use negative exponents (’9.8 m*s^-2′)
- use either a space or a ‘*’ to separate units (’9.8 ms^-2′ == ‘9.8 1/ms^2′)
- ruby-units understands all SI prefixes, and a few others as well
Unit Compatibility
Sometimes it is helpful to know if two units are ‘compatible’. Compatible units can be converted into each other, so ‘feet’ and ‘meters’ are compatbile, but ‘feet’ and ‘liters’ are not.
-
unit1= ‘1 feet’.unit
-
unit2 = ‘1 meter’.unit
-
unit3 = ‘1 liter’.unit
-
-
unit1 =~ unit2 #=>true
-
unit1 =~ unit3 #=>false
-
-
unit1.compatible? unit2 #=> true
-
unit1.compatible_with? unit3 #=>false
Unit Conversion
Units can be converted to each other so long as they are ‘compatible’. Ruby-units will throw an exception if units need to be compatible, but aren’t, so be sure to trap those exceptions when malformed input is possible.
Explicit Conversion
Explicit unit conversion occurs when the user asks for it. There are a couple of ways to force conversion to a particular unit.
-
unit = "1 mm".unit
-
unit >> "ft"
-
unit.to("inches")
-
unit2.to(unit1) # converts unit2 to same units as unit1
Implicit Conversion
There are times when unit conversions are implied or assumed for simplicity. For example, when adding two units, the gem will convert the second unit to the same base units as the first prior to doing the math.
-
unit1 = "1 meter".unit
-
unit2 = "50 cm".unit
-
result = unit1 + unit2 #=> 1.5 m
Unit Math
Unit objects come in really handy when doing complex math calculations:
-
pr = "1 atm".unit
-
n = "1 mol".unit
-
R = "8.3144 J/mol*degK".unit
-
T = "0 tempC".unit
-
v = (n*R*T)/pr # ideal gas law
-
p v.to_s("l") #=> 22.4 l
You can add, multiply, subtract, and divide units as you can with any Numeric class. You can also exponentiate or root them, although I restrict roots to integer values, since ‘m^0.5′ doesn’t really make any sense.
As an added bonus, all Trig functions (sin, cos, tan, sinh, …) can accept units that are compatible with radians. The values will be converted to radians before returning the result. So you can do this..
-
Math.sin("90 deg".unit) #=> 1.0
Temperatures
Note that we specified the temperature in this equation as a ‘tempC’. Specifying a temperature will convert that unit into the equivalent number of degrees kelvin. So in this case, “0 tempC”.unit => 273.15 degK.
This is necessary to make the calculations work out right. Most times unit conversions are done by just adjusting the size of the units, but temperatures require you to also specify the zero point on the scale.
You can convert ‘degree’ units (like ‘degC’, ‘degF’, ‘degR’, or ‘degK’) to a temperature this way…
This really only makes sense when the value represents the degrees between absolute zero and the point of interest. Only the user knows when that is the case, so use it carefully.
Time and Date Math
Ruby-units understands a wide range of time units, and can convert back and forth between them with ease. Nothing new there.
However, ruby-units can add and subtract time units from Date, DateTime, and Time objects. Throw in a few rails-esque helpers and you can write code like this…
-
one_hour_from_now = "1 h".from_now
-
in_five_minutes = Time.in("5 min")
-
an_hour_ago = "1 h".ago
-
next_week = Time.now + "1 week".unit
-
waiting_for = "min".until(one_hour_from_now)
-
days_to_christmas = "days".until("12/25/06")
-
age = "years".since("4/24/69")
Formatting Output
You can format the output of a Unit object by using the “.to_s” function and string format specifiers…
-
length = "1 mm".unit
-
length.to_s("%0.2f") #=> "1.00 mm"
-
height = "6 ft 4 in".unit.to_s(:ft) #=> 6′4"
-
weight = "8.25 lbs".unit.to_s(:lbs) #=> 8 lbs, 4 oz
-
time = "1.5 h".unit.to_s("%H:%M") #=> 1:30
Miscellaneous Stuff
You can create ranges of units, so long as they have scalar integers.
-
( U("1 mm") .. U("5 mm") ).map #=>[ 1 mm, 2 mm, 3 mm, 4 mm, 5mm]
If a unit is ‘unitless?’ then it can be converted back to other types of Numerics.
Note that ‘Unit’ objects are pretty slow compared to more common ones like Integers and Floats, so if performance is a big issue, you might want to consider using these sparingly.
Defining new units
You can define custom units by adding a code block like this..
-
class Unit < Numeric
-
@@USER_DEFINITIONS =
-
{‘<inchworm>’ => [%w{inworm inchworm}, 0.0254, :length, %w{<meter>} ],
-
’<cell>’ => [%w{cells cell}, 1, :counting, %w{<each>}],
-
’<habenero>’ => [%{degH}, 100, :temperature, %w{<celcius>}]}
-
Unit.setup
-
end
The format for the array is [%w{primary_name synonyms}, conversion_factor, unit_type, %w{
Useful References
Wikipedia: Units of Measurement
Filed by Kevin Olbrich at 3:23 pm under Ruby, gems, ruby-units
4 Comments
This looks nice. I am a little wary to use it in critical projects though without typed objects. I guess my ideal API would be something like:
a = Unit::Hour.new(1)
a.value #=> 1
a.class #=> Unit::Hour
Unit::Hour.descriptor #=> “hour” # can override or assign to support other languages easily
Unit::Hour.compatible_with? Unit::Minute #=> true
a.to_s #=> “1″
a.inspect #=> “1 hour”
Etc.
Then the class system can handle implicit conversions between types in a very rigorous way, and can also be overridden when necessary (what if you want Saturn years?). My guess is that you would see a speed improvement too this way.
What do you think?
Hi, great Gem, thanks! I found some trouble with inches to feet formatting:
irb(main):023:0> (’47 inches’).unit.to_s(:ft)
=> “3′11\”"
irb(main):024:0> (’47.2 inches’).unit.to_s(:ft)
=> “3′11\”"
irb(main):025:0> (’47.5 inches’).unit.to_s(:ft)
=> “3′11\”"
irb(main):026:0> (’47.9 inches’).unit.to_s(:ft)
=> “3′11\”"
irb(main):027:0> (’48 inches’).unit.to_s(:ft)
=> “3′11\”"
irb(main):028:0> (’49 inches’).unit.to_s(:ft)
=> “4′1\”"
Should not statements 25, 26, 27 return 4′ ?
I would patch this myself but I don’t know how.
Thank you for your contribution! Keep up the good work!
Eric
Hi nice gem, its almost exactly what ive been looking for.
I was hoping to use it to tell me if units are compatible with each other, but in this situation it doesnt do what i need :
“1mg/kg”.unit.compatible_with? “ml/l”
I guess that you have assumed here that the density is 1?
You cant convert mg/kg into ml/l without knowing the density. Would it be easily possible to add a method something along the lines of :
“1mg/kg”.unit.compatible_with_no_assumptions? “ml/l”
I may attempt to modify your code myself, but if you could give me any tips then that would be great.
Otherwise this would be perfect for me.
Cheers
Chris
Chris,
The compatibility check really only checks to see if units are freely convertible from one to the other. I’m not quite sure what you are trying to accomplish here since ‘mg/kg’ is a unitless expression. You can create complex expressions if you need to so something like:
density_of_solvent = ‘1 g/ml’.unit
volume_of_solvent = ‘100 ml’.unit
mass_of_solvent = density_of_solvent * volume_of_solvent