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!

montrealmike
  • 11,433
  • 10
  • 64
  • 86
  • possible duplicate of [How to find substring in ruby?](http://stackoverflow.com/questions/8258517/how-to-find-substring-in-ruby) – the Tin Man Jan 24 '12 at 01:20

4 Answers4

2

I believe you mean include?

Rob Di Marco
  • 43,054
  • 9
  • 66
  • 56
1

I believe you are looking for include?

"ab123de".include?("123")
Gabe Kopley
  • 16,281
  • 5
  • 47
  • 60
Justin Pihony
  • 66,056
  • 18
  • 147
  • 180
0

include?

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

Adam Pope
  • 3,234
  • 23
  • 32
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

Community
  • 1
  • 1
montrealmike
  • 11,433
  • 10
  • 64
  • 86
  • 3
    Just as a FYI, there are more Ruby-like ways of doing it: `'hello'['lo']` or `'hello'[/lo/]`. – the Tin Man Jan 24 '12 at 01: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 – montrealmike Jan 25 '12 at 19:51