Luigi
Luigi

Reputation: 5603

How do I count substrings within array of strings?

I have an array:

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

Now I need to count the number of times Passive is seen. How can I count the number of occurrences a substring is seen within strings inside of an array?

Upvotes: 0

Views: 180

Answers (3)

hirolau
hirolau

Reputation: 13901

Another way to do it:

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

Upvotes: 0

Luigi
Luigi

Reputation: 5603

I found an answer within grep.

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

This will suffice for my purpose.

Upvotes: 0

sawa
sawa

Reputation: 168091

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

Upvotes: 4

Related Questions