运维开发网

ruby-on-rails – 如何获取Rails数组中值的实例数?

运维开发网 https://www.qedev.com 2020-07-31 22:45 出处:网络 作者:运维开发网整理
说我有这样的数组: ["white", "red", "blue", "red", "white", "green", "red", "blue", "white", "orange"] 我想通过数组创建一个新数组,其中包含每个颜色以及它在原始数组中出现的次数. 因此,在新阵列中,它会报告“白色”出现3次,“蓝色”出现2次等等…… 我该怎么做呢? counts = Hash.new(0) colo
说我有这样的数组:

["white", "red", "blue", "red", "white", "green", "red", "blue", "white", "orange"]

我想通过数组创建一个新数组,其中包含每个颜色以及它在原始数组中出现的次数.

因此,在新阵列中,它会报告“白色”出现3次,“蓝色”出现2次等等……

我该怎么做呢?

counts = Hash.new(0)
colors.each do |color|
    counts[color] += 1
end
0

精彩评论

暂无评论...
验证码 换一张
取 消