如何计算字符串数组中的子字符串?

时间:2013-10-11 20:54:06

标签: ruby arrays string count

我有一个数组:

["Passive: 8", "Passive: 9", "Neutral: 3"]

现在我需要计算看到Passive的次数。如何计算在数组内的字符串中看到子串的出现次数?

3 个答案:

答案 0 :(得分:4)

["Passive: 8", "Passive: 9", "Neutral: 3"].grep(/Passive/).count
# => 2

答案 1 :(得分:0)

我在grep内找到了答案。

arr.grep(/^Passive/).each do |element|
  ...
end

这足以达到我的目的。

答案 2 :(得分:0)

另一种方法:

array.count{|x|x['Passive']}