0

I need to search over an array to find out which objects contain a specific string. The method must take two inputs.

This is a one-input method that works, and returns all objects with the letter t:

def my_array_finding_method(source)
  source.grep(/t/)
end

my_array_finding_method(array)

This does not work:

def my_array_finding_method(source, thing_to_find)
  source.grep(/thing_to_find/)
end

my_array_finding_method(array, "t")

I must modify the second bit of code to work. How can I do so?

2 Answers 2

2

You have to interpolate the variable name. Otherwise, it is just interpreted as plain text.

source.grep(/#{thing_to_find}/)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This is exactly what I needed, and will be very helpful in the future. As this is my first question, and a very basic one, I'm sure it's clear that I'm really new to Ruby/coding.
0

You don't have to use a regular expression:

def my_array_finding_method(source, thing_to_find)
  source.select { |s| s.include?(thing_to_find) }
end

arr = %w| It's true that cats have nine lives. |
   #=> ["It's", "true", "that", "cats", "have", "nine", "lives."] 
my_array_finding_method(array, "t")
   #=> ["It's", "true", "that", "cats"] 

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.