Class: NumberNameString::Convert

Inherits:
Object
  • Object
show all
Defined in:
lib/number_name_string/convert.rb

Overview

Handles conversion logic, takes full number (string or numeric), parses and accumulates results from lookup tables

Instance Method Summary collapse

Constructor Details

#initialize(num = nil) ⇒ Convert

Returns a new instance of Convert.



5
6
7
8
9
# File 'lib/number_name_string/convert.rb', line 5

def initialize(num = nil)
  @lookup = Lookup.instance
  @num = num
  @num_struct = Struct.new(:word, :type, :number) 
end

Instance Method Details

#[](arg = @num) ⇒ Object Also known as: <<



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/number_name_string/convert.rb', line 11

def [](arg = @num)
  if arg.is_a? Fixnum
    num_to_string arg
  elsif arg.is_a? String 
    string_to_num arg
  elsif arg.is_a? Symbol 
    string_to_num arg.to_s
  else
    raise NumberNameStringError.new("Invalid arg type: #{arg.class.name}")
  end
end

#num_to_string(num = @num, type = :cardinal) ⇒ Object

Converts a number to a string

Parameters:

  • num (Integer) (defaults to: @num)

    number to convert

  • type (Symbol) (defaults to: :cardinal)

    convert to type :cardinal or :ordinal



54
55
56
57
58
59
60
# File 'lib/number_name_string/convert.rb', line 54

def num_to_string(num = @num, type = :cardinal)
  name = ''
  num_to_triplets(num).each_with_index.reverse_each do |triplet, index| 
    name += " #{name_triplet triplet} #{SCALES[index]}" if triplet > 0
  end 
  name == '' ? 'zero' : name.sub(/^\s*/, '').sub(/\s*$/, '')
end

#string_to_num(arg = @num) ⇒ Object

Converts a string to a number

Parameters:

  • arg (String) (defaults to: @num)

    number to convert



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/number_name_string/convert.rb', line 29

def string_to_num(arg = @num)
  total = 0
  triplet = Triplet.new
  words = num_string_to_array arg
  marker = words.length
  while marker > 0 
    marker -= 1
    word = words[marker]
    if word.type == :number
      triplet << word.number
    end
    if word.type == :scale || marker == 0
      triplet.scale = word.number if word.type == :scale
      total += triplet.to_i
      triplet.reset
    end
  end
  total
end