我试图制作一个从其他数组收集单个字符串的数组,然后创建一个散列,计算estimate.bottom
中包含的每个字符串的数量。底部belongs_to
估计。
我的问题是,它目前不读取单个字符串,但数组作为一个整体。因此,如果底部是["a", "b"]
, ["a"]
和["b"]
,哈希的底部计数将是{["a"]=>1, ["b"]=>1, ["a", "b"]=>1}
而不是{["a"]=>2, ["b"]=>2}
@in_bottom = []
@estimates.each do |est|
@in_bottom << est.bottom
end
@bottom_count = Hash.new(0)
@in_bottom.each { |in_bottom| @bottom_count[in_bottom] += 1 }
我如何使方法迭代通过各个字符串,使bottom_count
正确工作?
- @in_bottom.each { |in_bottom| @bottom_count[in_bottom] += 1 }
+ @in_bottom.flatten.each { |in_bottom| @bottom_count[in_bottom] += 1 }
参见文档数组flatten方法