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
source
share