有没有一个 Ruby 方法,它接受一个字符串和一个默认值,并将其转换为整数(如果字符串表示整数),否则返回默认值?
更新:
我认为以下答案更好:
这里有证据说明为什么要避免异常:
class String
def try_to_i(default = nil)
/^\d+$/ === self ? to_i : default
end
end
这里有证据说明为什么要避免异常:
> 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