我有array
:
@a = ["P1 - D", "P3 - M", "P1 - D", "P1 - M", "P1 - D", "P1 - D", "P1 - D", "P1 - D", "P1 - D", "P1 - D", "P1 - D", "P1 - D", "P1 - M", "P2 - D", "P2 - D", "P2 - D", "P2 - M", "P2 - M", "P3 - D", "P3 - D", "P - D", "P1 - M", "P - D", "P - D", "Post - D", "S1 - D", "P1 - M"]
每个string
都基于页面# - 设备。所以P1 - D
是: Page1 - 桌面 & P3 - M
是: Page3 - 移动
如何找到string
内array
有多少{strong> D 或 M ?
答案 0 :(得分:4)
a.group_by { |e| e[-1] }.each_with_object({}) { |(k, v), hash| hash[k] = v.count }
#=> {"D"=>20, "M"=>7}
步骤:
groups = a.group_by { |e| e[-1] }
# {
# "D"=> ["P1 - D", "P1 - D", "P1 - D", "P1 - D", "P1 - D", "P1 - D", "P1 - D", "P1 - D", "P1 - D", "P1 - D", "P2 - D", "P2 - D", "P2 - D", "P3 - D", "P3 - D", "P - D", "P - D", "P - D", "Post - D", "S1 - D"],
# "M"=> ["P3 - M", "P1 - M", "P1 - M", "P2 - M", "P2 - M", "P1 - M", "P1 - M"]
# }
group_counts = groups.each_with_object({}) { |(k, v), hash| hash[k] = v.count }
#=> {"D"=>20, "M"=>7}
group_counts['M']
#=> 20
使用Ruby 2.4+,您可以使用Hash#transform_values
(积分转到Alex Golubenko :)):
a.group_by { |e| e[-1] }.transform_values(&:size)
#=> {"D"=>20, "M"=>7}
答案 1 :(得分:3)
可能的解决方案:
@a.group_by { |e| e[-1] }.map {|e, a| [e, a.size]}.to_h
=> {"D"=>20, "M"=>7}
答案 2 :(得分:2)
@a = ["P1 - D", "P3 - M", "P1 - D", "P1 - M", "P1 - D", "P1 - D", "P1 - D", "P1 - D", "P1 - D", "P1 - D", "P1 - D", "P1 - D", "P1 - M", "P2 - D", "P2 - D", "P2 - D", "P2 - M", "P2 - M", "P3 - D", "P3 - D", "P - D", "P1 - M", "P - D", "P - D", "Post - D", "S1 - D", "P1 - M"]
@a.count { |string| string.match(/D|M/) }
#=> 27
答案 3 :(得分:1)
@a.select { |word| word.include?('D') || word.include?('M') }.size
# => 27
答案 4 :(得分:1)
如果您只想要总数,可以使用:
@a.grep(/D|M/).count
#=> 27
如果你想要小计,这应该是最有效的方法,因为它不会创建任何临时数组:
@a.each_with_object(Hash.new(0)) { |string, count| count[string[-1]] += 1 }
#=> {"D"=>20, "M"=>7}