chief
chief

Reputation: 740

map and scan array

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

Answers (3)

mu is too short
mu is too short

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

Lars Haugseth
Lars Haugseth

Reputation: 14881

array_name.grep /\bcalifornia\b/i
# => ["this is california", "welcome to california"]

Upvotes: 3

Anil
Anil

Reputation: 3919

a = array_name.select{|b| b.match /\b(california)\b/i)}

Upvotes: 0

Related Questions