title: Convert Ruby String to Integer with default value
body: <p>Is there a Ruby method that takes a string and a default value and converts it to integer if the string represents integer or returns the default value otherwise?</p>
  
  <p><strong>update</strong>
  I think the following answer is preferable:</p>
  
  <pre><code>class String
    def try_to_i(default = nil)
      /^\d+$/ === self ? to_i : default
    end
  end
  </code></pre>
  
  <p>Here is evidence why you should avoid exceptions: </p>
  
  <pre><code>&gt; def time; t = Time.now; yield; Time.now - t end
  
  &gt; time { 1000000.times { |i| ('_' &lt;&lt; i.to_s) =~ /\d+/ } }
  =&gt; 1.3491532 
  &gt; time { 1000000.times { |i| Integer.new('_' &lt;&lt; i.to_s) rescue nil } }
  =&gt; 27.190596426 
  </code></pre>