Q:

How to convert an English string of a number into a float (e.g. "twenty-six"=>26.0)

I'm building a chatbot and I want to be able to parse strings representing numerical amounts that represent a human age. When I ask "How old are you?" the user should be able to input "26" or "twenty-six" and have the bot understand it as 26.0. The method should handle converting fractions to decimals.
Examples:
parse("six")              # => 6.0
parse("twenty-five")      # => 25.0
parse("three and a half") # => 3.5

Is there a gem that handles this in Ruby already, or is it easy enough to write a simple parse method?

A:

This is a solution that just looks for number words in the input string and adds them together. This works in English for ages < 100.
def parse(string)
  dict = {
    half: 0.5, 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,
    fourteen: 14, fifteen: 15, sixteen: 16,
    seventeen: 17, eighteen: 18, nineteen: 19,
    twenty: 20, thirty: 30, forty: 40, fifty: 50,
    sixty: 60, seventy: 70, eighty: 80, ninety: 90
  }

  age = 0.0

  dict.each do |s, n|
    # Scans string for each number name, adding numeric value if found
    age += n if string[/\b#{s}\b/]
  end

  return age
end

parse "six"              # => 6.0
parse "twenty-five"      # => 25.0
parse "three and a half" # => 3.5
parse "four and twenty"  # => 24.0

