 <p>here is a slightly better solution that would still allow you to have nil values </p> <p>(please note that nil.to_i is 0 as well as any "text".to_i is also 0)</p> <pre><code>def my_method(str) Integer(str.gsub(/\s/, '')) rescue ArgumentError =&gt; e nil end </code></pre> <p>Example of use:</p> <pre><code>my_method('1000') =&gt; 1000 my_method('1 000') =&gt; 1000 my_method(' ') =&gt; nil my_method('some_text') =&gt; nil my_method('1.000') =&gt; nil my_method('1,000') =&gt; nil </code></pre> <p>If you want to treat <code>.</code> and <code>,</code> you can adapt the regex in gsub.</p>