![](/img/trans.png)
[英]Ruby on Rails: TypeError (No implicit conversion of String into Integer)
[英]TypeError - no implicit conversion of String into Integer in array Ruby on Rails
我正在尝试制作一个输出以下内容的区域: [@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]]
我当前收到TypeError - no implicit conversion of String into Integer:
错误TypeError - no implicit conversion of String into Integer:
在下面的@monthly_value_created[i] << @months[i]
中。
这是我的代码:
@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
如何避免此错误?
您可以使用Array#zip
@months.zip(@monthly_idea_value).map &:flatten
如果@monthly_idea_value
是整数数组而不是数组数组,则不需要映射和展平。
可能会更有效:
@months.map.each_with_index do |month, index|
[month, @monthly_idea_value[index][0]]
end
因此,您的代码中有两个错误。
首先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的方法更好,也更红宝石:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.