是否存在一个Ruby方法,它接受一个字符串和一个默认值,并在字符串表示整数或者返回默认值时将其转换为整数?将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
你是什么意思的“包含整数”? – 2012-04-26 11:42:22
'“不成熟的优化是一切罪恶的根源” - Donald Knuth – Reactormonk 2012-04-27 08:28:06