如何统计Rails数组中特定值的实例数量?
- 内容介绍
- 文章标签
- 相关推荐
本文共计168个文字,预计阅读时间需要1分钟。
请告诉我这样的数组:[“white, red, blue, red, white, green, red, blue, white, orange]。我想通过数组创建一个新数组,其中包含每个颜色以及它在原始数组中出现的次数。”
说我有这样的数组:["white", "red", "blue", "red", "white", "green", "red", "blue", "white", "orange"]
我想通过数组创建一个新数组,其中包含每个颜色以及它在原始数组中出现的次数.
因此,在新阵列中,它会报告“白色”出现3次,“蓝色”出现2次等等……
我该怎么做呢?
counts = Hash.new(0) colors.each do |color| counts[color] += 1 end
本文共计168个文字,预计阅读时间需要1分钟。
请告诉我这样的数组:[“white, red, blue, red, white, green, red, blue, white, orange]。我想通过数组创建一个新数组,其中包含每个颜色以及它在原始数组中出现的次数。”
说我有这样的数组:["white", "red", "blue", "red", "white", "green", "red", "blue", "white", "orange"]
我想通过数组创建一个新数组,其中包含每个颜色以及它在原始数组中出现的次数.
因此,在新阵列中,它会报告“白色”出现3次,“蓝色”出现2次等等……
我该怎么做呢?
counts = Hash.new(0) colors.each do |color| counts[color] += 1 end

