ruby - Strictly convert string to integer (or nil) -
For web programming, the number comes in the form of string but to_i
is passed to " 5abc "from
to 5
and " abc "
to 0
. To catch these two incorrect answers, I wrote:
def number_or_nil (s) number = s.to_i number = zero if (number.to_s! = S) return number expiration
Is there a conservative and more natural way of completing this conversion and is finding out that the string is not to be used as a number?
integer ('5 BCI)') # = & gt; ArgumentError: Invalid value for integer (): "5abc" integer ('5') # = & gt; 5
If you want the behavior to be returned to that number, even if no string can be changed, you will still need your number_ or_nil method.
def number_or_nil (string) integer (string || ''), rescue argument error zero end
You should be careful to avoid any special exception . A bare defense (such as "Rescue zero") will be avoided by any error that is obtained from standard error and can interfere with the execution of your program as you do not expect. Integer () will increase an ArgumentError, so specify this.
If you do not want to deal with the exceptions and just like the small version of your number / or NNIL, then you can take advantage of the inbound return values and write it:
def number_or_nil (string) num = string.to_i num if num.to_s == string end number_or_anyil '5' # => 5 number_or_nil '5bc' # = & gt; Zero
This will work as you expect.
Comments
Post a Comment