Class: TrickBag::Numeric::KmgtNumericString::ToNumberConverter

Inherits:
Object
  • Object
show all
Defined in:
lib/trick_bag/numeric/kmgt_numeric_string.rb

Overview

This class is here to simplify implementation and is not intended to be instantiated by users of this module.

Instance Method Summary collapse

Constructor Details

#initialize(string) ⇒ ToNumberConverter

Returns a new instance of ToNumberConverter.



77
78
79
80
# File 'lib/trick_bag/numeric/kmgt_numeric_string.rb', line 77

def initialize(string)
  @string = string.dup.gsub('_', '')
  assert_valid_input(@string)
end

Instance Method Details

#assert_valid_input(string) ⇒ Object



82
83
84
85
86
87
88
# File 'lib/trick_bag/numeric/kmgt_numeric_string.rb', line 82

def assert_valid_input(string)
  unless VALID_STRING_REGEX.match(string)
    raise ArgumentError.new(
        "Bad arg (#{string}); must be an integer, optionally followed by one of [" +
        MULTIPLIERS.keys.join + '], optionally with underscores.')
  end
end

#to_numberObject



90
91
92
93
94
95
96
97
98
# File 'lib/trick_bag/numeric/kmgt_numeric_string.rb', line 90

def to_number
  last_char = @string[-1]
  if VALID_STRING_SUFFIXES.include?(last_char)
    multiplier = MULTIPLIERS[last_char]
    Integer(@string.chop) * multiplier
  else
    Integer(@string)
  end
end