Safe integer parsing in Ruby

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

    Re: Chris's answer

    Your implementation let's things like "1a" or "b2" through. How about this instead:

    def safeParse2(strToParse)
      if strToParse =~ /\A\d+\Z/
        strToParse.to_i
      else
        raise Exception
      end
    end
    
    ["100", "1a", "b2", "t"].each do |number|
      begin
        puts safeParse2(number)
      rescue Exception
        puts "#{number} is invalid"
      end
    end
    

    This outputs:

    100
    1a is invalid
    b2 is invalid
    t is invalid
    

提交回复
热议问题