Safe integer parsing in Ruby

后端 未结 8 688
眼角桃花
眼角桃花 2020-12-02 06:51

I have a string, say \'123\', and I want to convert it to the integer 123.

I know you can simply do some_string.to_i, but that

8条回答
  •  醉话见心
    2020-12-02 07:12

    Another unexpected behavior with the accepted solution (with 1.8, 1.9 is ok):

    >> Integer(:foobar)
    => 26017
    >> Integer(:yikes)
    => 26025
    

    so if you're not sure what is being passed in, make sure you add a .to_s.

提交回复
热议问题