Skip to content

Instantly share code, notes, and snippets.

@rodloboz
Last active February 26, 2020 16:49
Show Gist options
  • Select an option

  • Save rodloboz/6c8d21462f0a8ea41720e19af6cb84d9 to your computer and use it in GitHub Desktop.

Select an option

Save rodloboz/6c8d21462f0a8ea41720e19af6cb84d9 to your computer and use it in GitHub Desktop.
Parse Int
NUMERALS_MAP = {
'zero' => 0,
'one' => 1,
'two' => 2,
'three' => 3,
'four' => 4,
'five' => 5,
'six' => 6,
'seven' => 7,
'eight' => 8,
'nine' => 9,
'ten' => 10,
'eleven' => 11,
'twelve' => 12,
'thirteen' => 13,
'sixteen' => 16,
'seventeen' => 17,
'eighteen' => 18,
'nineteen' => 19,
'twenty' => 20,
'thirty' => 30,
'forty' => 40,
'fifty' => 50,
'sixty' => 60,
'seventy' => 70,
'eighty' => 80,
'ninety' => 90,
'hundred' => 100,
'thousand' => 1000,
'million' => 1000000
}
def parse_int(string)
numerals = string.split(/[\s,-]/).reject { |n| n == 'and' }
raise ArgumentError, 'Argument is not a numeral' unless numerals.all? { |n| NUMERALS_MAP.key? n }
numbers = numerals.map { |n| NUMERALS_MAP[n] }
total = 0
numbers.each_with_index do |number, index|
next if number == 100
if numbers[index + 1] == 100
total += number * numbers[index + 1]
elsif number == 1000
total *= number
else
total += number
end
end
total
end
puts parse_int('one') == 1
puts parse_int('twenty') == 20
puts parse_int('ninety-nine') == 99
puts parse_int('two hundred forty-six') == 246
puts parse_int('seven hundred eighty-three thousand nine hundred and nineteen') == 783919
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment