prajeesh
prajeesh

Reputation: 2382

Get the number of occurrences of a specific pattern in a ruby array

Consider that i have the following

array = ["Master Bathroom - Toilet", "Guest Bathroom - Toilet", "Kitchen - Faucet", "Master Bathroom - Faucet"]

I need to find out the number of times the pattern "Toilet" appears in the array.

In this case the result should be 2. Any idea on how to do this?

Upvotes: 1

Views: 85

Answers (1)

mrzasa
mrzasa

Reputation: 23317

You can use Array#count:

array.count{|e| e.include?('Toilet') }

String#include? checks if string contains a substring. If you want to match a regular expression, you can use =~ with a regex instead.

Upvotes: 3

Related Questions