ruby-on-rails - 如何修复 Ruby 中的 "String to Integer"错误

标签 ruby-on-rails

我需要根据不同的费率确定运费。

在过去的 5 个小时里我尝试了各种各样的东西。 如果我应该使用 .to_s .to_f,我已经尝试过但做得不正确。

if (weight < 2)

     rate = 0.10

   elsif ((weight >= 2) or (weight < 10))

     rate = 0.20

   elsif ((weight >= 10) or (weight < 40))

     rate = 0.30

   elsif ((weight >= 40) or (weight < 70))

     rate = 0.50

   elsif ((weight >= 70) or (weight < 100))

     rate = 0.75

   else (weight >= 100)

     rate = 0.90

end

rate = rate.to_i

ship_cost = weight * price * rate

ship_cost = ship_cost.to_i

结果应该显示应用费率后的运费。我不断遇到“字符串到整数”错误。

最佳答案

问题是乘法中的一个或多个变量是一个字符串,这会导致您收到 TypeError 错误,如下所示:

'a' * 'b' #  '*': no implicit conversion of String into Integer (TypeError)

如果要抑制错误,可以手动将它们转换为整数或 float 。这意味着如果字符串没有数字表示,它将返回 0:

'asd'.to_i  # 0
'1'.to_i.   # 1
'-9.9'.to_i # -9
'-9.9'.to_f # -9.9

或者,您可以使用保存最小值和最大值的“字典”来处理rate分配,weight可以返回X。创建一个从最小值到最大值的范围,并询问它是否包含您可以指定其值的权重值:

dict = {
  [-Float::INFINITY, 2]  => 0.10,
  [2, 10]                => 0.20,
  [10, 40]               => 0.30,
  [40, 70]               => 0.50,
  [70, 100]              => 0.75,
  [100, Float::INFINITY] => 0.90
}

p dict.find { |(start, finish), _| (start...finish).include?(-42.12) }.last # 0.1
p dict.find { |(start, finish), _| (start...finish).include?(0) }.last      # 0.1
p dict.find { |(start, finish), _| (start...finish).include?(1) }.last      # 0.1
p dict.find { |(start, finish), _| (start...finish).include?(23) }.last     # 0.3
p dict.find { |(start, finish), _| (start...finish).include?(101) }.last    # 0.9

关于ruby-on-rails - 如何修复 Ruby 中的 "String to Integer"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58671594/

相关文章:

ruby-on-rails - Ruby 方法 Double Splat 与 Hash

jquery - 如何在 select2 中添加自定义标签

ruby-on-rails - 新 Rails 3 项目中的未定义方法 `use_transactional_fixtures='

ruby-on-rails - 如何通过 Rspec 测试 Redis 锁

ruby-on-rails - 为 Ruby gem 创建安装生成器

ruby-on-rails - 确保 has_many :through association is unique on creation

ruby-on-rails - RAILS3 : to_JSON with multiple objects and includes

ios - 从 iPhone 通过的 Stripe 卡身份验证在服务器上失败

ruby-on-rails - 为什么 Jekyll 在我创建新帖子时会创建包含 index.html 文件的新目录?

ruby-on-rails - Ruby 未定义方法 `[]' 为 nil :NilClass (NoMethodError) error