【问题标题】:TypeError - no implicit conversion of String into Integer in array Ruby on RailsTypeError - Ruby on Rails 数组中没有将字符串隐式转换为整数
【发布时间】:2015-06-12 15:00:39
【问题描述】:

我正在尝试创建一个输出以下内容的区域:[@month, @monthly_count],以便完整的输出如下所示:[["January", 0], ["February", 0], ["March", 0], ["April", 2], ["May", 3], ["June", 19], ["July", 0], ["August", 0], ["September", 0], ["October", 0], ["November", 0], ["December", 0]]

我目前在下面的@monthly_value_created[i] << @months[i] 行上收到TypeError - no implicit conversion of String into Integer: 的错误。

这是我的代码:

@months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
@monthly_idea_value = [[0], [0], [0], [3], [35], [744], [0], [0], [0], [0], [0], [0]] 
#Array of arrays of integers isn't best, but unless it's causing the error I'm not worried about it right now.
#Bc the .flatten! method at the end fixes the output

      @monthly_value_created = Array.new(12){Array.new}
      i = 0
      12.times do |i|
        @monthly_value_created[i] << @months[i]
        @monthly_value_created[i] << @monthly_idea_value[i]
        @monthly_value_created.flatten!
        i += 1
      end

我怎样才能避免这个错误?

【问题讨论】:

    标签: ruby-on-rails arrays ruby ruby-on-rails-4


    【解决方案1】:

    您可以使用Array#zip

    @months.zip(@monthly_idea_value).map &:flatten
    

    如果@monthly_idea_value 是整数数组,而不是数组数组,则无需映射和展平。

    【讨论】:

    • 这会取代整个迭代吗?从 i=0 到 i +=1?
    • 是的。而且你的代码有很多错误,2call-chaos已经详细解释过了。阅读这篇文章,并了解循环在 Ruby 中的工作原理。
    【解决方案2】:

    这样做可能更有效:

    @months.map.each_with_index do |month, index|
      [month, @monthly_idea_value[index][0]]
    end
    

    【讨论】:

      【解决方案3】:

      所以你的代码中有两个错误。

      首先是自己递增i,而#times 已经传递了变量。

      你犯的第二个错误是你扁平化了错误的东西(你只想扁平化子数组而不是你构建的数组结构。

      @months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
      @monthly_idea_value = [[0], [0], [0], [3], [35], [744], [0], [0], [0], [0], [0], [0]]
      
      @monthly_value_created = Array.new(12){Array.new}
      12.times do |i|
        @monthly_value_created[i] << @months[i]
        @monthly_value_created[i] << @monthly_idea_value[i]
        @monthly_value_created[i].flatten!
      end
      
      => [["January", 0], ["February", 0], ["March", 0], ["April", 3], ["May", 35], ["June", 744], ["July", 0], ["August", 0], ["September", 0], ["October", 0], ["November", 0], []]
      

      仍然 fylooi 或 Santhosh 的方法更好,更红宝石 :)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-11
        • 1970-01-01
        • 2014-06-21
        • 1970-01-01
        • 2021-03-28
        • 1970-01-01
        • 2014-01-14
        • 1970-01-01
        相关资源
        最近更新 更多