Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There's not a built in function to say if a string is effectively an integer, but you can easily make your own:</p> <pre><code>class String def int Integer(self) rescue nil end end </code></pre> <p>This works because the Kernel method <code>Integer()</code> throws an error if the string can't be converted to an integer, and the inline <code>rescue nil</code> turns that error into a nil.</p> <pre><code>Integer("1") -&gt; 1 Integer("1x") -&gt; nil Integer("x") -&gt; nil </code></pre> <p>and thus:</p> <pre><code>"1".int -&gt; 1 (which in boolean terms is `true`) "1x".int -&gt; nil "x".int -&gt; nil </code></pre> <p>You could alter the function to return <code>true</code> in the true cases, instead of the integer itself, but if you're testing the string to see if it's an integer, chances are you want to use that integer for something! I very commonly do stuff like this:</p> <pre><code>if i = str.int # do stuff with the integer i else # error handling for non-integer strings end </code></pre> <p>Although if the assignment in a test position offends you, you can always do it like this:</p> <pre><code>i = str.int if i # do stuff with the integer i else # error handling for non-integer strings end </code></pre> <p>Either way, this method only does the conversion once, which if you have to do a lot of these, may be a significant speed advantage.</p> <p>[Changed function name from <code>int?</code> to <code>int</code> to avoid implying it should return just true/false.]</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload