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?

1

I believe you are looking for include?

"ab123de".include?("123")
0

include?

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

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
  • 3
    Just 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

Not the answer you're looking for? Browse other questions tagged or ask your own question.