Skip to content

Converting quantities to different units

spatchcock edited this page Dec 14, 2011 · 6 revisions

Quantities can be converted to alternative units easily using the Quantity#to method. The alternative units must be dimensionally compatible with the original quantity’s unit, i.e. it must represent the same physical quantity (e.g. mass, length, time, velocity, acceleration, etc.). (The valid alternative units can be discovered using the Unit#alternatives method). The new unit can be specified in any of the formats valid for the Unit.for method, i.e. unit name, symbol, label or object. (These operations return whole quantity objects, but it is easier for illustrative purposes to call #to_s in these examples.)

my_quantity = Quantity.new(50, "km")
my_quantity.to_s                                   #=> "50.0 km"
my_quantity.to(:ft).to_s                           #=> "164041.994750656 ft"

my_quantity = Quantity.new(12, "parsec")
my_quantity.to_s                                   #=> "12.0 pc"
my_quantity.to("light year").to_s                  #=> "39.1387725894302 ly"

my_quantity = 1000.kilowatt_hours
my_quantity.to_s                                   #=> "1000.0 kWh"
new_unit = Unit.for("joule")
my_quantity.to(new_unit).to_s(:name)               #=> "3600000000.0 joules"

Appending the argument to the method name is also supported:

my_quantity = 45.litres
my_quantity.to_s(:name)                            #=> "45.0 litres"
my_quantity.to_gal.to_s(:name)                     #=> "11.8877416777883 US liquid gallons"

You can also easily convert a quantity into its SI equivalent unit:

50.mi.to_si.to_s                                   #=> "80467.2 m"
45.L.to_si.to_s                                    #=> "0.045 m^3"
6000.inches_of_mercury.to_si.to_s                  #=> "20318334.0 Pa"
65.miles_per_hour.to_si.to_si                      #=> "29.0576 m/s"

Clone this wiki locally