Arrays Ruby—计算数组中包含两个字符之一的字符串数

Arrays Ruby—计算数组中包含两个字符之一的字符串数,arrays,ruby,include,Arrays,Ruby,Include,我有一个数组: @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",

我有一个
数组

@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"]
每个
字符串
都基于页面设备。因此
P1-D
is:Page1-Desktop&
P3-M
is:Page3-Mobile

如何找到
数组中
字符串
中有多少个DM

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+,您可以使用(积分转到:):

可能的解决办法:

@a.group_by { |e| e[-1] }.map {|e, a| [e, a.size]}.to_h
=> {"D"=>20, "M"=>7}

如果您只想要总数,可以使用:

@a.grep(/D|M/).count
#=> 27
如果需要小计,这应该是最有效的方法,因为它不会创建任何临时数组:

@a.each_with_object(Hash.new(0)) { |string, count| count[string[-1]] += 1 }
#=> {"D"=>20, "M"=>7}

谢谢@Andrey,当我运行这个时,我得到了错误:
未定义的方法last
请看一下这个链接:@user6589814这很奇怪。。。您可以使用
group_by{el|el[-1]}
然后
a.group_by{e|e[-1]}.transform_值(&:size)
;)@AlexGolubenko
转换值
!!很酷,以前没有使用过它。
String#last
不是Rails方法吗?答案可能值得一提,你想要一个总数,即27或类似于
{“D”=>20,“M”=>7}
。你需要编辑标题,使其与问题一致。也许,“计算数组中包含两个字符中任意一个的字符串数。”当然,谢谢@CarySwovelandI,我最喜欢这个,因为它效率高,可读性最好。提前进行
count
可以告诉读者你在做什么。在Ruby v2.4+中,您可以使用
string.match/D\M/
,可以说读起来更好。当然,您可以使用
/[DM]/
而不是
/D}M/
。我建议你删除第一行。由于OP定义了
@a
,因此它是多余的,并且会降低您的答案的视觉吸引力。
@a.select { |word| word.include?('D') || word.include?('M') }.size
# => 27
@a.grep(/D|M/).count
#=> 27
@a.each_with_object(Hash.new(0)) { |string, count| count[string[-1]] += 1 }
#=> {"D"=>20, "M"=>7}