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!
-
possible duplicate of How to find substring in ruby?– the Tin ManCommented Jan 24, 2012 at 1:20
Add a comment
|
4 Answers
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
-
3Just as a FYI, there are more Ruby-like ways of doing it:
'hello'['lo']
or'hello'[/lo/]
. Commented Jan 24, 2012 at 1:22 -
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 Commented Jan 25, 2012 at 19:51