-
Notifications
You must be signed in to change notification settings - Fork 4
Operating on quantities
spatchcock edited this page Dec 14, 2011
·
3 revisions
Performing mathematical operations on quantities is straightforward, using the obvious syntax for addition, subtraction, multiplication, etc. For addition and subtraction, both quantities must represent the same physical quantity (i.e. mass, length, time, energy, etc.), although if the units on each differ from one another, the unit associated with the receiver takes priority and any conversions handled accordingly. (As before, these operations return new quantity objects, but the examples call the #to_s method for illustrative purposes.)
(50.km + 25.km).to_s #=> "75.0 km"
(1000.grams - 127.grams).to_s #=> "873.0 g"
(1000.g - 1.kg).to_s #=> "0.0 g"
(35.ft + 5.yd).to_s #=> "50.0 ft"
20.5.gal + 18.seconds #=> InvalidObjectError: "Cannot add or subtract
# Quantities with different dimensions"Any quantities can be used in division or multiplication operations - the units are handled appropriately, in most cases producing compound units.
(50.m * 10.m).to_s #=> "500.0 m^2"
(120.miles / 2.5.hours).to_s(:name) #=> "48.0 miles per hour"
("We drove for 3.5 hours".to_q * "Our speed was 75 miles per hour".to_q).to_s(:name)
#=> "262.5 miles"Raising quantities to powers also uses familiar syntax:
(20.m ** 2).to_s #=> "400.0 m^2"