【问题标题】:Can't Sum up ruby integers不能总结红宝石整数
【发布时间】:2015-12-23 09:20:30
【问题描述】:

我在尝试将每个 boxes.percent 与局部变量 percent 相加时遇到此错误。

这里是错误:

Fixnum 没有隐式转换为数组

我的代码:

<% percent = 0, shares = 0 %>
<% @modification.boxes.each do |d|
  percent = percent + d.percent #here is problem, at least rails told me that 
  shares = shares + d.shares  
end %>

<% unless percent == 100 %>  
  Total percent needs to be 100%!
<% end %>

<% unless shares == @modification.entity.total_number %> 
  Not correct number!
<% end %>

问题出在哪里?在数据库中,框的 percentshares 都是整数。

【问题讨论】:

  • 解释一下这些变量/方法是什么。
  • 共享堆栈跟踪,从顶部开始至少几行
  • @sawa d.percentd.shares 是每个 box 的百分比和份额计数。都是 DB 中的整数。局部变量 percentshares 用于将所有内容一起计算。我解释过你想要什么吗?
  • 如何创建@modification 以及boxes 方法的外观如何?
  • @modification 是数据库表。每个修改都有很多框。所以它们都是数据库表。

标签: ruby math integer


【解决方案1】:

这是你的问题:

您将percentshares 声明为percent = 0, shares = 0。这将创建百分比为Array,值为[0,0]。 而是将两者都声明为percent = 0; shares = 0。 (注意分号而不是逗号)

2.1.5 :042 > percent = 0, shares = 0
 => [0, 0] 
2.1.5 :043 > percent
 => [0, 0] 
2.1.5 :044 > percent.class
 => Array 

【讨论】:

    【解决方案2】:

    作业没有按预期进行:

    percent = 0, shares = 0
    

    因为它被解释为:

    percent = (0, (shares = 0))
    

    相当于:

    shares = 0
    percent = 0, shares
    

    最后一行implicitly creates an array。你也可以写:

    shares = 0
    percent = [0, shares]
    

    “修复”其实很简单。您必须将变量移到左侧,将值移到右侧:

    percent, shares = 0, 0
    

    这叫multiple assignment


    顺便说一句,您也可以使用sum,而不是自己循环:

    percent = @modification.boxes.sum(&:percent)
    shares  = @modification.boxes.sum(&:shares)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-06
      • 2023-03-19
      • 2015-02-24
      • 1970-01-01
      • 2019-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多