-
Notifications
You must be signed in to change notification settings - Fork 4
Introduction to quantities
spatchcock edited this page Jan 19, 2012
·
1 revision
Quantities are represented by instances of the Quantify::Quantity class. There are a number of ways to initialize quantity objects, each of which require a numerical value and a unit. The unit can be specified using string or symbol representations of any of the unit descriptors described here (name, symbol, label) or with a unit object:
Use the Quantity constructor:
Quantity.new(50, "kilometre") #=> <Quantify::Quantity>
Quantity.new(12, "parsecs") #=> <Quantify::Quantity>
Quantity.new(28.5, :MJ) #=> <Quantify::Quantity>
unit = Unit.ton_uk #=> <Quantify::Unit::NonSI>
Quantity.new(1000, unit) #=> <Quantify::Quantity>Or the shorthand:
50.kilometre #=> <Quantify::Quantity>
12.parsecs #=> <Quantify::Quantity>
28.5.MJ #=> <Quantify::Quantity>
1000.ton_uk #=> <Quantify::Quantity>Alternatively, quantities can be parsed from strings based on a numerical values and valid unit descriptors. In these cases, an array is returned containing quantity objects representing each recognised quantity:
Quantity.parse("50 kilometres") #=> Array of quantity objects
"0.18 volts".to_q #=> Array of quantity objects
"The quantity measured 0.18 volts per second".to_q #=> Array of quantity objectsThese objects can be interrogated:
my_quantity = Quantity.new(50, "kilometres")
my_quantity.value #=> 50
my_quantity.unit #=> <Quantify::Unit::SI>
my_quantity.unit.name #=> "kilometre"
my_quantity.unit.symbol #=> "kg"
my_quantity.to_s #=> "50 kg"
my_quantity.to_s(:name) #=> "50 kilograms"
my_quantity.represents #=> "mass"