0

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?

3 Answers 3

4
["Passive: 8", "Passive: 9", "Neutral: 3"].grep(/Passive/).count
# => 2
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, beat me to it. This is also cleaner as it's one line of code. Thanks.
0

I found an answer within grep.

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

This will suffice for my purpose.

3 Comments

This doesn't answer the question you asked, it only finds the ones matching, and doesn't count them.
Agreed - This isn't complete, but I could iterate over each element and add one each time. However, sawa's answer is much more efficient.
@sawa's answer is also idiomatic Ruby. That it's a single line of code isn't important.
0

Another way to do it:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.