String.include? / start_with? / end_with?
Methods that check whether a string contains a specific substring, or whether it starts or ends with a specific string.
Syntax
# Checks whether the string contains the specified substring. string.include?(search_string) # Checks whether the string starts with the specified prefix. string.start_with?(prefix) # Checks whether the string ends with the specified suffix. string.end_with?(suffix)
Method List
| Method | Description |
|---|---|
| include?(str) | Returns true if the string contains the argument string. Case-sensitive. |
| start_with?(prefix, ...) | Returns true if the string starts with the specified prefix. You can pass multiple arguments; returns true if any one of them matches. |
| end_with?(suffix, ...) | Returns true if the string ends with the specified suffix. Multiple arguments are accepted. |
Sample Code
sentence = "Ruby is an object-oriented language."
# Check whether a substring exists.
puts sentence.include?("Ruby") # true
puts sentence.include?("Python") # false
puts sentence.include?("ruby") # false (case-sensitive)
# Check the beginning of the string.
puts sentence.start_with?("Ruby") # true
puts sentence.start_with?("Python") # false
# Multiple candidates can be specified.
puts sentence.start_with?("Python", "Ruby", "Java") # true
# Check the end of the string.
puts sentence.end_with?("language.") # true
puts sentence.end_with?("language") # false
# Useful for URL validation.
url = "https://example.com"
if url.start_with?("https://")
puts "This is a secure URL." # This line is printed.
else
puts "Not HTTPS."
end
# Useful for checking file extensions.
filename = "image.png"
puts filename.end_with?(".png", ".jpg", ".gif") # true
Notes
include? checks whether the string contains the specified substring. Comparison is case-sensitive, so if you want a case-insensitive search, convert the string to a consistent case with downcase before comparing.
start_with? and end_with? both accept multiple arguments and return true if any one of them matches. They are handy in practical situations such as checking URL schemes or file extensions.
To get the position (index) of a substring, use index / rindex.
If you find any errors or copyright issues, please contact us.