How many strings in the array contain either of these two characters?

2026-04-10 06:501阅读0评论SEO资讯
  • 内容介绍
  • 相关推荐

本文共计328个文字,预计阅读时间需要2分钟。

How many strings in the array contain either of these two characters?

我有这个数组:@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]

我有这个数组:

@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"]

每个字符串都基于Page# – Device.所以P1 – D是:Page1 – 桌面& P3 – M是:Page3 – 移动

How many strings in the array contain either of these two characters?

如何找到数组中有多少字符串有D或M?

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}

本文共计328个文字,预计阅读时间需要2分钟。

How many strings in the array contain either of these two characters?

我有这个数组:@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]

我有这个数组:

@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"]

每个字符串都基于Page# – Device.所以P1 – D是:Page1 – 桌面& P3 – M是:Page3 – 移动

How many strings in the array contain either of these two characters?

如何找到数组中有多少字符串有D或M?

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}