Class: NumberNameString::Convert
- Inherits:
-
Object
- Object
- NumberNameString::Convert
- Defined in:
- lib/number_name_string/convert.rb
Constant Summary collapse
- ONES =
TODO: convert to arrays for multiple spellings
- [forty, fourty] - [hundred, hundered] %W{ #{} one two three four five six seven eight nine }
- ONES_ZERO =
%W{ zero one two three four five six seven eight nine }
- TEENS =
%w{ ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen }
- TENS =
%W{ #{} #{} twenty thirty forty fifty sixty seventy eighty ninety }
- SCALE =
%W{ #{} thousand million billion trillion quadrillion quintillion sextillion septillion octillion nonillion decillion undecillion duodecillion tredecillion quattuordecillion quindecillion sexdecillion septendecillion octodecillion novemdecillion vigintillion }
- SCALE_MAX =
(SCALE.length - 1) * 3
Instance Method Summary collapse
Instance Method Details
#[](arg) ⇒ Object Also known as: <<
19 20 21 22 23 24 25 26 27 |
# File 'lib/number_name_string/convert.rb', line 19 def [](arg) if arg.is_a? Fixnum to_s arg elsif arg.is_a? String to_i arg else raise NumberNameStringError.new("Invalid arg type: #{arg.class.name}") end end |
#to_i(arg) ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/number_name_string/convert.rb', line 31 def to_i(arg) num = 0 words = arg.downcase.gsub('-', '').split(/\s+/) while word = words.shift accum = 0 # (sub_hundred | ones(false) hundred [sub_hundred] )[scale]] if sub_hundred?(word) if ones?(word, false) && hundred?(words[0]) accum += ones?(word) * 100 words.shift word = words.shift else accum += sub_hundred?(word) end word = words.shift if scale? word accum *= scale? word end end # puts "accum: #{accum}" num += accum end num end |
#to_s(num, include_zero = true) ⇒ Object
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/number_name_string/convert.rb', line 56 def to_s(num, include_zero = true) case digits = num.to_s.length when 1 include_zero ? ONES_ZERO[num] : ONES[num] when 2 num < 20 ? TEENS[num - 10] : "#{TENS[num / 10]}#{ONES[num % 10]}" when 3 "#{ONES[num / 100]} hundred#{space_pad(to_s(num % 100, false))}" when (4..SCALE_MAX) zeros = 10 ** (((digits - 1) / 3) * 3) "%s%s%s" % [to_s(num / zeros, false), space_pad(SCALE[(digits - 1) / 3]), space_pad(to_s(num % zeros, false))] else raise NumberNameStringError.new('Number out of range') end end |