Reputation: 740
I want to list out all of the strings in an array that include a given keyword.
array_name = ["this is california", "hawaii", "washington", "welcome to california"]
a = array_name.map { |s| s.scan(/\b(california)\b/i) }.flatten
# => ["california", "california"]
The above will create a new array of strings where each string is "california". How do I make a new array with the entire original string?
Upvotes: 0
Views: 1916
Reputation: 434865
You're using the wrong method if you're trying to find strings that match, you want select
:
array_name.select { |s| s.match(/\bcalifornia\b/i) }
# ["this is california", "welcome to california"]
The select
method:
Returns an array containing all elements of enum for which block is not false.
Upvotes: 3
Reputation: 14881
array_name.grep /\bcalifornia\b/i
# => ["this is california", "welcome to california"]
Upvotes: 3