简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM