Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 integer if the string represents integer or returns the 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

Here is evidence 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 
like image 928
Alexey Avatar asked Apr 26 '12 11:04

Alexey


1 Answers

There's #to_i and Integer() to convert. The first has a default of 0, the second one raises an ArgumentError.

class String
  def to_integer(default)
    Integer(self)
  rescue ArgumentError
    default
  end
end
like image 166
Reactormonk Avatar answered Oct 13 '22 22:10

Reactormonk