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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With