Convert string numbers( in word format) to integer ruby

后端 未结 4 1997
没有蜡笔的小新
没有蜡笔的小新 2021-01-24 18:43

If you have a string ten, is it possible to convert it to an integer 10 in Ruby? (maybe in rails?)

I value the developers at tryruby.org, and i

4条回答
  •  孤城傲影
    2021-01-24 18:49

    This is a simple lookup of strings to their numeric equivalent:

    str_to_int_hash = {
      'zero'  => 0,
      'one'   => 1,
      'two'   => 2,
      'three' => 3,
      'four'  => 4,
      'five'  => 5,
      'six'   => 6,
      'seven' => 7,
      'eight' => 8,
      'nine'  => 9,
      'ten'   => 10
    }
    
    str_to_int_hash['ten']
    => 10
    

    It's obvious there are many other missing entries, but it illustrates the idea.

    If you want to go from a number to the string, this is the starting point:

    int_to_str_hash = Hash[str_to_int_hash.map{ |k,v| [v,k] }]
    int_to_str_hash[10]
    => "ten"
    

提交回复
热议问题