<p>I have a string, say <code>'123'</code>, and I want to convert it to the integer <code>123</code>.</p>

<p>I know you can simply do <code>some_string.to_i</code>, but that converts <code>'lolipops'</code> to <code>0</code>, which is not the effect I have in mind. I want it to blow up in my face when I try to convert something invalid, with a nice and painful <code>Exception</code>. Otherwise, I can't distinguish between a valid <code>0</code> and something that just isn't a number at all.</p>

<p><strong>EDIT:</strong> I was looking for the standard way of doing it, without regex trickery.</p>

[{'answer_id': 49282, 'author': 'Slartibartfast', 'author_id': 4433, 'author_profile': 'https://Stackoverflow.com/users/4433', 'pm_score': 9, 'selected': True, 'text': '<p>Ruby has this functionality built in:</p>\n\n<pre><code>Integer(\'1001\')                                    # =&gt; 1001  \nInteger(\'1001 nights\')  \n# ArgumentError: invalid value for Integer: "1001 nights"  \n</code></pre>\n\n<p>As noted in answer by <a href="https://stackoverflow.com/questions/49274/safe-integer-parsing-in-ruby/53359#53359">Joseph Pecoraro</a>, you might want to watch for strings that are valid non-decimal numbers, such as those starting with <code>0x</code> for hex and <code>0b</code> for binary, and potentially more tricky numbers starting with zero that will be parsed as octal.</p>\n\n<p>Ruby 1.9.2 added optional second argument for radix so above issue can be avoided:</p>\n\n<pre><code>Integer(\'23\')                                     # =&gt; 23\nInteger(\'0x23\')                                   # =&gt; 35\nInteger(\'023\')                                    # =&gt; 19\nInteger(\'0x23\', 10)\n# =&gt; #&lt;ArgumentError: invalid value for Integer: "0x23"&gt;\nInteger(\'023\', 10)                                # =&gt; 23\n</code></pre>\n'}, {'answer_id': 49283, 'author': 'Purfideas', 'author_id': 4615, 'author_profile': 'https://Stackoverflow.com/users/4615', 'pm_score': 5, 'selected': False, 'text': '<p>This might work:</p>\n\n<pre><code>i.to_i if i.match(/^\\d+$/)\n</code></pre>\n'}, {'answer_id': 49287, 'author': 'Paul Wicks', 'author_id': 85, 'author_profile': 'https://Stackoverflow.com/users/85', 'pm_score': 2, 'selected': False, 'text': '<pre><code>someString = "asdfasd123"\nnumber = someString.to_i\nif someString != number.to_s\n  puts "oops, this isn\'t a number"\nend\n</code></pre>\n\n<p>Probably not the cleanest way to do it, but should work.</p>\n'}, {'answer_id': 53359, 'author': 'Joseph Pecoraro', 'author_id': 792, 'author_profile': 'https://Stackoverflow.com/users/792', 'pm_score': 5, 'selected': False, 'text': "<p>Also be aware of the affects that the current accepted solution may have on parsing hex, octal, and binary numbers:</p>\n\n<pre><code>&gt;&gt; Integer('0x15')\n# =&gt; 21  \n&gt;&gt; Integer('0b10')\n# =&gt; 2  \n&gt;&gt; Integer('077')\n# =&gt; 63\n</code></pre>\n\n<p>In Ruby numbers that start with <code>0x</code> or <code>0X</code> are hex, <code>0b</code> or <code>0B</code> are binary, and just <code>0</code> 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 <code>/\\d+/</code> regular expressions, etc.</p>\n"}, {'answer_id': 53840, 'author': 'metavida', 'author_id': 5539, 'author_profile': 'https://Stackoverflow.com/users/5539', 'pm_score': 1, 'selected': False, 'text': '<p>Re: <a href="https://stackoverflow.com/questions/49274/safe-integer-parsing-in-ruby#49280">Chris\'s answer</a></p>\n\n<p>Your implementation let\'s things like "1a" or "b2" through. How about this instead:</p>\n\n<pre><code>def safeParse2(strToParse)\n  if strToParse =~ /\\A\\d+\\Z/\n    strToParse.to_i\n  else\n    raise Exception\n  end\nend\n\n["100", "1a", "b2", "t"].each do |number|\n  begin\n    puts safeParse2(number)\n  rescue Exception\n    puts "#{number} is invalid"\n  end\nend\n</code></pre>\n\n<p>This outputs:</p>\n\n<pre><code>100\n1a is invalid\nb2 is invalid\nt is invalid\n</code></pre>\n'}, {'answer_id': 131714, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>I had to deal with this in my last project, and my implementation was similar, but a bit different:</p>\n\n<pre><code>class NotAnIntError &lt; StandardError \nend\n\nclass String\n  def is_int?    \n    self =~ /^-?[0-9]+$/\n  end\n\n  def safe_to_i\n    return self.to_i if is_int?\n    raise NotAnIntError, "The string \'#{self}\' is not a valid integer.", caller\n  end\nend\n\nclass Integer\n  def safe_to_i\n    return self\n  end            \nend\n\nclass StringExtensions &lt; Test::Unit::TestCase\n\n  def test_is_int\n    assert "98234".is_int?\n    assert "-2342".is_int?\n    assert "02342".is_int?\n    assert !"+342".is_int?\n    assert !"3-42".is_int?\n    assert !"342.234".is_int?\n    assert !"a342".is_int?\n    assert !"342a".is_int?\n  end\n\n  def test_safe_to_i\n    assert 234234 == 234234.safe_to_i\n    assert 237 == "237".safe_to_i\n    begin\n      "a word".safe_to_i\n      fail \'safe_to_i did not raise the expected error.\'\n    rescue NotAnIntError \n      # this is what we expect..\n    end\n  end\n\nend\n</code></pre>\n'}, {'answer_id': 2551994, 'author': 'Jaime Cham', 'author_id': 304734, 'author_profile': 'https://Stackoverflow.com/users/304734', 'pm_score': 4, 'selected': False, 'text': "<p>Another unexpected behavior with the accepted solution (with 1.8, 1.9 is ok):</p>\n\n<pre><code>&gt;&gt; Integer(:foobar)\n=&gt; 26017\n&gt;&gt; Integer(:yikes)\n=&gt; 26025\n</code></pre>\n\n<p>so if you're not sure what is being passed in, make sure you add a <code>.to_s</code>.</p>\n"}, {'answer_id': 16526935, 'author': 'ian', 'author_id': 335847, 'author_profile': 'https://Stackoverflow.com/users/335847', 'pm_score': 3, 'selected': False, 'text': '<p>I like Myron\'s answer but it suffers from the Ruby disease of <em>"I no longer use Java/C# so I\'m never going to use inheritance again"</em>. Opening any class can be fraught with danger and should be used sparingly, <strong><em>especially</em></strong> 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.</p>\n\n<pre><code>class IntegerInString &lt; String\n\n  def initialize( s )\n    fail ArgumentError, "The string \'#{s}\' is not an integer in a string, it\'s just a string." unless s =~ /^\\-?[0-9]+$/\n    super\n  end\nend\n</code></pre>\n\n<p>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.</p>\n\n<pre><code>n = IntegerInString.new "2"\nn.to_i\n# =&gt; 2\n\nIntegerInString.new "blob"\nArgumentError: The string \'blob\' is not an integer in a string, it\'s just a string.\n</code></pre>\n\n<p>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 <strong>clarity</strong>. Naming an object via its variable name <em>and</em> its class name makes things <em>much</em> clearer.</p>\n'}]
['https://Stackoverflow.com/questions/49274', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2018/']