Convert Ruby String to Integer with default value

Is there a Ruby method that takes a string and a default value and converts it to an integer if the string represents an integer or returns a default value otherwise?

Update I think the following answer is preferable:

class String
  def try_to_i(default = nil)
    /^\d+$/ === self ? to_i : default
  end
end

This is why you should avoid exceptions:

> def time; t = Time.now; yield; Time.now - t end

> time { 1000000.times { |i| ('_' << i.to_s) =~ /\d+/ } }
=> 1.3491532 
> time { 1000000.times { |i| Integer.new('_' << i.to_s) rescue nil } }
=> 27.190596426 
+5
source share
3 answers

You will need to do this yourself, possibly using a regular expression to check the string:

def try_to_i(str, default = nil)
  str =~ /^-?\d+$/ ? str.to_i : default
end
+2
source

Here #to_iand Integer()for conversion. The first has a default value of 0, the second raises an ArgumentError.

class String
  def to_integer(default)
    Integer(self)
  rescue ArgumentError
    default
  end
end
+8
source

- :

int_value = (stringVar.match(/^(\d+)$/) && $1.to_i) || default_value

, , , int .

-1

All Articles