Safe integer parsing in Ruby

后端 未结 8 687
眼角桃花
眼角桃花 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:06

    Also be aware of the affects that the current accepted solution may have on parsing hex, octal, and binary numbers:

    >> Integer('0x15')
    # => 21  
    >> Integer('0b10')
    # => 2  
    >> Integer('077')
    # => 63
    

    In Ruby numbers that start with 0x or 0X are hex, 0b or 0B are binary, and just 0 are octal. If this is not the desired behavior you may want to combine that with some of the other solutions that check if the string matches a pattern first. Like the /\d+/ regular expressions, etc.

提交回复
热议问题