Strictly convert string to integer (or nil)

后端 未结 3 835
醉酒成梦
醉酒成梦 2020-12-29 19:34

For web programming, numbers come in as strings. but to_i will convert \"5abc\" to 5 and \"abc\" to 0, both

3条回答
  •  孤城傲影
    2020-12-29 19:53

    Use a simple regex to check str is an integer.

    def number_or_nil(str)
       str.to_i if str[/^-?\d+$/] and str.line.size == 1
    end
    

提交回复
热议问题