Method: RubyUnits::Unit#to_s
- Defined in:
- lib/ruby_units/unit.rb
#to_s(target_units = nil) ⇒ String
Generate human readable output. If the name of a unit is passed, the unit will first be converted to the target unit before output. some named conversions are available
You can also pass a standard format string (i.e., ‘%0.2f’) or a strftime format string.
output is cached so subsequent calls for the same format will be fast
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 |
# File 'lib/ruby_units/unit.rb', line 519 def to_s(target_units=nil) out = @output[target_units] if out return out else case target_units when :ft inches = self.convert_to("in").scalar.to_int out = "#{(inches / 12).truncate}\'#{(inches % 12).round}\"" when :lbs ounces = self.convert_to("oz").scalar.to_int out = "#{(ounces / 16).truncate} lbs, #{(ounces % 16).round} oz" when String out = case target_units when /(%[\-+\.\w#]+)\s*(.+)*/ #format string like '%0.2f in' begin if $2 #unit specified, need to convert self.convert_to($2).to_s($1) else "#{$1 % @scalar} #{$2 || self.units}".strip end rescue # parse it like a strftime format string (DateTime.new(0) + self).strftime(target_units) end when /(\S+)/ #unit only 'mm' or '1/mm' self.convert_to($1).to_s else raise "unhandled case" end else out = case @scalar when Rational "#{@scalar} #{self.units}" else "#{'%g' % @scalar} #{self.units}" end.strip end @output[target_units] = out return out end end |