Class: Subunit
- Inherits:
-
Object
- Object
- Subunit
- Defined in:
- lib/subunit.rb
Overview
file: subunit.rb
Instance Attribute Summary collapse
-
#to_a ⇒ Object
readonly
Returns the value of attribute to_a.
-
#to_h ⇒ Object
readonly
Returns the value of attribute to_h.
-
#to_i ⇒ Object
readonly
Returns the value of attribute to_i.
Instance Method Summary collapse
-
#initialize(raw_units = {}, obj) ⇒ Subunit
constructor
A new instance of Subunit.
-
#strfunit(s) ⇒ Object
usage: Subunit.new(units=hours:60, seconds: 661)\ .strfunit(“%x”) #=> 11m 1s.
- #to_s(omit: [], verbose: true) ⇒ Object
Constructor Details
#initialize(raw_units = {}, obj) ⇒ Subunit
Returns a new instance of Subunit.
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/subunit.rb', line 9 def initialize(raw_units={}, obj) @debug = false if obj.is_a? Array then a = obj[0..-2] len = raw_units.to_a.length val = ([0]*(len-1) + a).slice(-(len), len).zip(raw_units.values)\ .inject(0) {|r,x| r + x.inject(:*) } @to_i = val + obj[-1] else raw_subunit = obj || 0 method((raw_units.class.to_s.downcase + '_units').to_sym)\ .call(raw_units, raw_subunit) end end |
Instance Attribute Details
#to_a ⇒ Object (readonly)
Returns the value of attribute to_a.
7 8 9 |
# File 'lib/subunit.rb', line 7 def to_a @to_a end |
#to_h ⇒ Object (readonly)
Returns the value of attribute to_h.
7 8 9 |
# File 'lib/subunit.rb', line 7 def to_h @to_h end |
#to_i ⇒ Object (readonly)
Returns the value of attribute to_i.
7 8 9 |
# File 'lib/subunit.rb', line 7 def to_i @to_i end |
Instance Method Details
#strfunit(s) ⇒ Object
usage: Subunit.new(units=hours:60, seconds: 661)\
.strfunit("%x") #=> 11m 1s
%x e.g. 11m 1s %X e.g. 11 minutes 1 second
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/subunit.rb', line 36 def strfunit(s) s.sub!('%x') do |x| to_h.map {|label, val| val.to_s + label[0]}.join(' ') end s.sub!('%X') do |x| to_h.map do |label, val| next if val == 0 label2 = val > 1 ? label.to_s : label.to_s.sub(/s$/,'') val.to_s + ' ' + label2 end.compact.join(' ') end s end |
#to_s(omit: [], verbose: true) ⇒ Object
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
# File 'lib/subunit.rb', line 57 def to_s(omit: [], verbose: true) if not verbose then r = self.to_a.reverse.take_while {|x| x > 0}.reverse\ .map {|x| "%02d" % x}.join(':') if r.length < 2 then return '00:00' elsif r.length == 2 return '00:' + r else return r end end h = @to_h omit.each {|x| h.delete x} list = h.to_a n = list.find {|_,v| v > 0 } a = list[list.index(n)..-1].map {|x|"%d %s" % x.reverse} duration = case a.length when 1 a.first when 2 a.join ' and ' else "%s and %s" % [a[0..-2].join(', '), a[-1]] end duration.gsub(/(\b1 \w+)s/, '\1') end |