9

I want to search through an array using a partial string, and then get the index where that string is found. For example:

a = ["This is line 1", "We have line 2 here", "and finally line 3", "potato"]
a.index("potato") # this returns 3
a.index("We have") # this returns nil

Using a.grep will return the full string, and using a.any? will return a correct true/false statement, but neither returns the index where the match was found, or at least I can't figure out how to do it.

I'm working on a piece of code that reads a file, looks for a specific header, and then returns the index of that header so it can use it as an offset for future searches. Without starting my search from a specific index, my other searches will get false positives.

3
  • ruby-doc.org/core-1.9.3/String.html#method-i-3D-7E Commented Jan 16, 2013 at 0:13
  • Do you want only the array index where the string was found, or the array index, plus the offset into the string in that array element? Commented Jan 16, 2013 at 0:15
  • Just the first one, but I would be interested in the second one just for future use, because that sounds like it would be very useful to know! Commented Jan 16, 2013 at 0:26

1 Answer 1

24

Use a block.

a.index{|s| s.include?("We have")}

or

a.index{|s| s =~ /We have/}
Sign up to request clarification or add additional context in comments.

1 Comment

Amazing! I thought include would only work with true/false, but I was wrong! This works perfectly, thank you!

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.