Safe integer parsing in Ruby

后端 未结 8 644
眼角桃花
眼角桃花 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
    someString = "asdfasd123"
    number = someString.to_i
    if someString != number.to_s
      puts "oops, this isn't a number"
    end
    

    Probably not the cleanest way to do it, but should work.

    0 讨论(0)
  • I like Myron's answer but it suffers from the Ruby disease of "I no longer use Java/C# so I'm never going to use inheritance again". Opening any class can be fraught with danger and should be used sparingly, especially when it's part of Ruby's core library. I'm not saying don't ever use it, but it's usually easy to avoid and that there are better options available, e.g.

    class IntegerInString < String
    
      def initialize( s )
        fail ArgumentError, "The string '#{s}' is not an integer in a string, it's just a string." unless s =~ /^\-?[0-9]+$/
        super
      end
    end
    

    Then when you wish to use a string that could be a number it's clear what you're doing and you don't clobber any core class, e.g.

    n = IntegerInString.new "2"
    n.to_i
    # => 2
    
    IntegerInString.new "blob"
    ArgumentError: The string 'blob' is not an integer in a string, it's just a string.
    

    You can add all sorts of other checks in the initialize, like checking for binary numbers etc. The main thing though, is that Ruby is for people and being for people means clarity. Naming an object via its variable name and its class name makes things much clearer.

    0 讨论(0)
提交回复
热议问题