Convert string numbers( in word format) to integer ruby

后端 未结 4 1999
没有蜡笔的小新
没有蜡笔的小新 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:45

    Since String#to_i picks out only the number characters, it will not work in the way you want. There may be some Rails method related to that, but it surely will not have the method name to_i because its behavior will conflict with the original intent of String#to_i.

    It is not only Strings that has to_i. NilClass, Time, Float, Rational (and perhaps some other classes) do as well.

    "3".to_i #=> 3
    "".to_i #=> 0
    nil.to_i #=> 0
    Time.now.to_i #=> 1353932622
    (3.0).to_i #=> 3
    Rational(10/3).to_i #=> 3
    

提交回复
热议问题