How to Find Index of Substring in Ruby: Simple Guide
In Ruby, you can find the index of a substring using the
String#index method. It returns the position of the first occurrence of the substring or nil if the substring is not found.Syntax
The String#index method is used to find the position of a substring inside a string.
string.index(substring): Returns the index of the first occurrence ofsubstring.- If the substring is not found, it returns
nil.
ruby
string.index(substring)
Example
This example shows how to find the index of a substring inside a string. It prints the index if found, or a message if not found.
ruby
text = "hello world" index = text.index("world") if index puts "Substring found at index: #{index}" else puts "Substring not found" end
Output
Substring found at index: 6
Common Pitfalls
One common mistake is expecting String#index to return -1 when the substring is not found. Instead, it returns nil. Always check for nil before using the result.
Also, String#index returns the first occurrence only. To find all occurrences, you need a different approach.
ruby
text = "hello world" index = text.index("ruby") if index.nil? puts "Substring not found" else puts "Substring found at index: #{index}" end
Output
Substring not found
Quick Reference
| Method | Description | Return Value |
|---|---|---|
| string.index(substring) | Finds first index of substring | Integer index or nil if not found |
| string.index(substring, start) | Finds index starting from position start | Integer index or nil |
| string.rindex(substring) | Finds last index of substring | Integer index or nil |
Key Takeaways
Use
String#index to find the first position of a substring in Ruby.If the substring is not found,
String#index returns nil, not -1.Always check for
nil before using the index result to avoid errors.To find the last occurrence, use
String#rindex.For multiple occurrences, you need to loop or use regular expressions.