0

Is there a present? method in ruby to check if a string is present within an other? I'd want to return as soon as a match is found since I will be checking for multiple substrings. Thanks!

1

4 Answers 4

2

I believe you mean include?

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

Comments

1

I believe you are looking for include?

"ab123de".include?("123")

Comments

0

include?

http://ruby-doc.org/core-1.9.3/String.html#method-i-include-3F

Comments

0

Sorry, found what i was looking for (because of the use of regexp):

index(regexp [, offset]) → fixnum or nil

Returns the index of the first occurrence of the given substring or pattern (regexp) in str. Returns nil if not found.

"hello".index('lo')            #=> 3
"hello".index('a')             #=> nil
"hello".index(?e)              #=> 1
"hello".index(/[aeiou]/, -3)   #=> 4

http://ruby-doc.org/core-1.9.3/String.html

i just used a loop checking if the index is nil

2 Comments

Just as a FYI, there are more Ruby-like ways of doing it: 'hello'['lo'] or 'hello'[/lo/].
Good to know, thanks! I think in this case i'll spend the extra 5 char nonetheless, just to make sure it's clear to everyone what is going on. EDIT: just to clarify for others 'hellohello'['lo'] => lo, not the index, but would still work since 'hell'['lo'] => nil

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.