0

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?

3
  • You may get more attention if you add Ruby to the title or somewhere in your question. I'm just saying because it wasn't obvious to me at first what language you were using. Commented Jun 3, 2012 at 3:33
  • 2
    @AlexW: It is tagged "ruby"... Commented Jun 3, 2012 at 3:34
  • I realize that. I am merely pointing out that it would get more attention from Ruby gurus if it had Ruby in the title or the body of his question. Commented Jun 3, 2012 at 3:36

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

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.