One of the most common operations a programmer use on strings is to check whether a string contains another string.
In this post, I will show you several methods for finishing this operation, with a little bit more analysis of the implementation.
1. Using include? method from string
The method named
include? will return
false as result, sample code is:
Note: This method is case sensitive. If you want to ignore case sensitive, you could do a
downcase() operation firstly.
2. Using regular expression
Regex matching in Ruby returns nil when the expression doesn’t match. When it matches, it returns the index of the character where the match happens.
Note: In Ruby, only
nil and the boolean
false are evaluated to false. Everything else(including an empty array, empty hash, or the integer 0) are evaluated to true.
Another benefit from regular expression: it’s a general pattern match for strings, for example:
3. Using  in string
You could also use
 in string, the usgage is as below:
Note: You maybe thought
 is actually same with
index will return the position of first occurrence, while
 will return a string same with parameter.
4. Rails: Using in operator
In Rails, a more idiom practice is like this:
Note: It’s only available in Rails, and not pure Ruby.
As an aspiring developer, you may curious about how the string matching is implemented in Ruby’s source code.
A little bit dig will find out the related C implementation in source code of string.c:
Let’s continue to check the function
rb_memsearch located at re.c:
By default, if system have defined a function called
memmem, Ruby will just call it directly. The
memmem() function is not specified in POSIX.1, but normally could be found in a system like Linux. It’s implemented with Glibc.
Otherwise, If a system doesn’t have
memmem, Ruby uses an algorithm called Rabin–Karp algorithm to do string pattern matching. It uses a rolling hash to quickly filter out positions of the text that cannot match the pattern and then checks for a match at the remaining positions.
index could all used to do pattern matching of strings.
In the source code of Ruby, we use
memmem or Rabin–Karp algorithm for string searching.