How to Check if String Contains Substring in Ruby
In Ruby, you can check if a string contains a substring using the
include? method, which returns true if the substring is found and false otherwise. Alternatively, you can use index or match methods for similar checks.Syntax
The most common way to check if a string contains a substring is using the include? method. It returns true if the substring exists inside the string, otherwise false.
Other methods include index, which returns the position of the substring or nil if not found, and match, which returns a match object or nil.
ruby
string.include?(substring) string.index(substring) string.match(substring)
Example
This example shows how to use include? to check if a string contains a substring and prints the result.
ruby
text = "Hello, welcome to Ruby programming!" substring = "Ruby" if text.include?(substring) puts "The text contains '#{substring}'." else puts "The text does not contain '#{substring}'." end
Output
The text contains 'Ruby'.
Common Pitfalls
A common mistake is to use == instead of include?, which checks for exact equality, not substring presence. Also, remember that include? is case-sensitive, so "ruby" and "Ruby" are different.
ruby
text = "Hello, Ruby!" # Wrong: checks if whole string equals substring puts text == "Ruby" # false # Right: checks if substring is inside string puts text.include?("Ruby") # true # Case sensitivity example puts text.include?("ruby") # false
Output
false
true
false
Quick Reference
| Method | Description | Returns |
|---|---|---|
| include?(substring) | Checks if substring exists in string | true or false |
| index(substring) | Finds position of substring or nil | Integer or nil |
| match(substring) | Matches substring using regex | MatchData or nil |
Key Takeaways
Use
include? to check if a string contains a substring easily and clearly.include? is case-sensitive; use downcase if you want case-insensitive checks.Avoid using
== when checking for substrings; it tests full string equality.index and match provide alternative ways to find substrings with more detail.