是否有一个 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
最佳答案
有#to_i
和Integer()
可以转换。第一个默认为
0,第二个引发 ArgumentError。
class String
def to_integer(default)
Integer(self)
rescue ArgumentError
default
end
end
关于ruby - 使用默认值将 Ruby 字符串转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10332650/