How to check whether a string contains a substring in Ruby
There are many ways to check whether a string contains a substring in Ruby.
The most common way is to use the include? method:
'hello'.include? 'll' # => true
'hello'.include? 'ol' # => false
If you need to check whether a string contains a regular expression, you can use the match? method:
'hello'.match? /ll/ # => true
'hello'.match? /ol/ # => false
If you need to check whether a string starts with a substring, you can use the start_with? method:
'hello'.start_with? 'he' # => true
'hello'.start_with? 'llo' # => false
If you need to check whether a string ends with a substring, you can use the end_with? method:
'hello'.end_with? 'llo' # => true
'hello'.end_with? 'ell' # => false
If you need to check whether a string contains a regular expression, you can use the match? method:
That formula is ambiguous and possibly misguiding!
A String may contain a regular expression, but that is not an argument to use the match() method.
You use a regular expression (with match() or any other technique), when you have a vague idea of what the string should contain or when you ensure that the string conforms to some rule.
Using match() is like widening the range of possible possitive results, in contrast to include? or the other methods presented above: A regular expression allows a multitude of possible substrings at various positions of the string.
In contrast, the String "This is a regular expression: /(?:--)+=literal\d+/, you see?"
does contain a regular expression.