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
You will have to code that yourself, possibly using a regular expression to check the string: