Skip to content

Introduction to units

spatchcock edited this page Apr 14, 2012 · 32 revisions

Units are handled by the Quantify::Unit module, with individual units represented by instances of the Quantify::Unit::Base class and its subclasses. Unit objects can be created and defined arbitrarily, but Quantify provides a comprehensive system of pre-configured units out of the box, which I’ll focus on here.

Known units are handled by calling the Unit.for method, together with one of three possible references for the unit required: the name, symbol or label. Names and symbols are simply the full (e.g. ‘centimetre’, ‘pound’, ‘kilowatt’) and abbreviated (‘cm’, ‘lb’, ‘kW’) conventional descriptors associated with each unit. Unit labels are unique references which follow the Java JScience API. Pluralized names are also supported. Providing any of these to the Unit.for method will return the associated unit, e.g.:

    Unit.for("kilometre")              #=> <Quantify::Unit::SI>
    Unit.for("parsecs")                #=> <Quantify::Unit::NonSI>
    Unit.for(:lb)                      #=> <Quantify::Unit::NonSI>
    Unit.for("ton_uk")                 #=> <Quantify::Unit::NonSI>

or, via the shorthand:

    Unit.kilometre                     #=> <Quantify::Unit::SI>
    Unit.lb                            #=> <Quantify::Unit::NonSI>
    Unit.ton_uk                        #=> <Quantify::Unit::NonSI>

The unit object can be interrogated in a variety of ways:

    my_unit = Unit.pound               #=> <Quantify::Unit::SI>
    my_unit.name                       #=> "pound"
    my_unit.pluralized_name            #=> "pounds"
    my_unit.symbol                     #=> "lb"
    my_unit.label                      #=> "lb"
    my_unit.measures                   #=> "mass"
    my_unit.si_unit.name               #=> "kilogram"
    my_unit.alternatives               #=> Array of unit objects
    my_unit.alternatives(:name)        #=> ["kilogram", "gram", "carat", "electron mass", "grain",
                                       #    "hundredweight long", "hundredweight short", "long ton",
                                       #    "ounce", "pennyweight", "short ton", "stone", "tonne",
                                       #    "unified atomic mass"]

Units can be multiplied, divided or raised to powers to produce compound units, for example:

    a_unit = Unit.kilowatt * Unit.hour
    a_unit.symbol                       #=> "kW h"

    another_unit = Unit.metre / Unit.second
    another_unit.name                  #=> "metres per second"

    yet_another_unit = Unit.metre ** 2
    yet_another_unit.symbol            #=> "m^2"

These operations are handled automatically when dealing with quantities, however, so it is often unnecessary to operate on unit objects directly in this way.

Clone this wiki locally