ruby - 使用默认值将 Ruby 字符串转换为整数

标签 ruby integer type-conversion

是否有一个 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_iInteger() 可以转换。第一个默认为 0,第二个引发 ArgumentError。

class String
  def to_integer(default)
    Integer(self)
  rescue ArgumentError
    default
  end
end

关于ruby - 使用默认值将 Ruby 字符串转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10332650/

相关文章:

ruby-on-rails - sidekiq 中的 perform_in 和 perform_async 有什么区别?

python - 如何操作整数/字符串中的数字?

r - R中整数类和数字类有什么区别

ruby-on-rails - 意外的 keyword_end,期望输入结束

ruby-on-rails - 如何在 rails application.rb 中加载多个 YAML 文件

ruby-on-rails - Devise_token_auth 冲突?

javascript - "value"参数不能是数字

Python 列表类型

c# - TryParse 创建内联参数?

c++ - "More than one operator + matches these operands"错误