Ruby example

How to check if a string contains a substring in Ruby

8 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Use include?: text.include?("fox") returns true or false. To test only the beginning or the end, use start_with?("abc") and end_with?(".rb"). For a pattern or a case-insensitive check, use match? with a regex: text.match?(/fox/i).

Ruby strings have no contains method and no in operator for substrings: the check is include?, and start_with?, end_with? and match? cover the rest. The sections below cover a plain substring with include?, prefixes and suffixes, regular expressions and case-insensitive checks, getting the position or the matched text with index and s[sub], counting occurrences with scan (and why count gives the wrong answer), and what happens when the string is nil, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1include?Recommended

string.include?(other) returns true when other appears anywhere in the string, false otherwise. It compares characters exactly, so it is case-sensitive, and the argument must be a string: a regex or a number raises a TypeError. It reads well after if and unless, which is how most Ruby code uses it. It is the same method name as Array#include?, which checks for an element rather than a substring.

include.rb
text = "The quick brown fox"

puts "fox? #{text.include?("fox")}"
puts "cat? #{text.include?("cat")}"

puts "Found a fox" if text.include?("fox")
puts "No cat here" unless text.include?("cat")

# include? is case-sensitive and matches anywhere
p text.include?("Quick")
p text.include?("ick bro")

# The empty string is in every string
p text.include?("")

# The argument must be a string, not a regex
begin
  text.include?(/fox/)
rescue TypeError => e
  puts "#{e.class}: #{e.message}"
end

# Coming from Python? "cat" in text is pattern matching:
# it binds "cat" to a variable named text and always matches
puts "matched" if "cat" in text
p text

Output

"Quick" is not found because the text has a lowercase q, while "ick bro" is found across a word boundary: include? knows nothing about words. The empty string counts as contained in every string, so check for an empty search term yourself if it can happen. Passing a regex prints TypeError: no implicit conversion of Regexp into String; use match? for patterns (section 3). The last two lines are the trap for Python readers: "cat" in text is valid Ruby, but a bare name in a pattern is a variable to bind, so it prints matched and text is now "cat", with no error.

2Starts with or ends with: start_with? and end_with?

Python's startswith and JavaScript's startsWith are start_with? and end_with? in Ruby (no s after start). Both take several arguments and return true if any of them matches, so a list of file extensions needs no loop. start_with? also accepts a regex, which is anchored at the start of the string; end_with? takes strings only. To remove a known prefix or suffix instead of testing for it, use delete_prefix and delete_suffix, which return the string unchanged when it does not match.

starts_with.rb
path = "/usr/local/bin/ruby"

p path.start_with?("/usr")
p path.end_with?("ruby")
p path.start_with?("usr")

# Several candidates: true if any of them matches
file = "report.csv"
p file.end_with?(".csv", ".tsv")
p file.start_with?("draft", "final")

# start_with? also takes a regex (end_with? does not)
p "v4.0.7".start_with?(/v\d/)
p "Hello".start_with?(/h/i)

begin
  "report.csv".end_with?(/csv/)
rescue TypeError => e
  puts "#{e.class}: #{e.message}"
end

# Strip a known prefix or suffix
p path.delete_prefix("/usr/local")
p file.delete_suffix(".csv")
p file.delete_suffix(".json")

Output

path.start_with?("usr") is false because the path begins with a slash. end_with?(".csv", ".tsv") is true since one of the two matches. The regex form makes case-insensitive prefixes easy: /h/i matches "Hello". Giving end_with? a regex prints the same TypeError as include?; for a pattern at the end, use match? with \z, as in file.match?(/\.csv\z/i). The last line prints "report.csv" unchanged because it has no .json suffix.

3Patterns and ignoring case: match? and =~

When the thing you look for is a pattern (a date, a word in any case, one of several words), use match? with a regex. It returns true or false and is the fastest regex check because it records nothing about the match. The older =~ operator returns the index where the match starts, or nil, which works in an if since any integer, even 0, is truthy in Ruby; it also stores the match in $~. For a case-insensitive contains, add the i flag, or downcase both sides and use include? (see converting a string to lowercase).

match.rb
log = "ERROR 2026-12-02: disk full"

# match? returns true or false
p log.match?(/\d{4}-\d{2}-\d{2}/)
p log.match?(/warn/i)

# =~ returns the index where the match starts, or nil
p log =~ /disk/
p log =~ /memory/
puts "has a date" if log =~ /\d{4}-\d{2}/

# =~ also stores the match in $~; match? skips that work
p $~[0]

# Case-insensitive contains: the i flag, or downcase both sides
p log.include?("error")
p log.match?(/error/i)
p log.downcase.include?("error")

# A string passed to match? is read as a regex
needle = "a.b"
p "axb".match?(needle)
p "axb".match?(Regexp.escape(needle))
p "axb".include?(needle)

Output

log =~ /disk/ prints 18, the position of disk, and a miss prints nil; $~[0] then holds "2026-12", the text the last =~ matched. The three case lines show that plain include? misses "ERROR" when you ask for "error", while both case-insensitive forms find it. The last block is a gotcha: match? turns a string argument into a regex, so the dot in "a.b" matches any character and "axb" matches. Wrap user input in Regexp.escape, or use include?, when you mean the literal text. casecmp? ignores case too, but it compares whole strings, not substrings.

4Get the position or the text: index and s[sub]

index returns where a substring (or a regex) first appears, or nil when it is absent, so it doubles as a contains check. rindex searches from the end, and a second argument says where to start. Unlike Python's find and JavaScript's indexOf, a miss is nil, not -1. The element reference s[sub] returns the substring itself when it is present and nil otherwise; with a regex, s[regex] returns the matched text and s[regex, 1] the first capture group.

position.rb
text = "one two three two one"

# index gives the position of the first match, or nil
p text.index("two")
p text.index("four")
p text.rindex("two")

# Start searching at a given position
p text.index("two", 5)

# index also takes a regex
p text.index(/t\w+e/)

# s[sub] returns the substring itself, or nil
p text["three"]
p text["four"]
puts "found two" if text["two"]

# s[regex] returns the match, s[regex, n] a capture group
p text[/t\w+e/]
p "id=42;name=ann"[/id=(\d+)/, 1]

# Every position of a substring
p text.enum_for(:scan, "two").map { Regexp.last_match.begin(0) }

Output

The first two starts at index 4 and the last at 14; starting the search at 5 skips the first one, so it finds 14 too. The regex /t\w+e/ skips two and matches three at 8, and text[/t\w+e/] returns that word. The capture-group form pulls "42" out of the string in one step. The last line lists every start position, [4, 14]: each scan step leaves its match in Regexp.last_match, whose begin(0) is the offset.

5Count occurrences: scan, not count

To count how many times a substring appears, use scan, which returns an array of every match, and take its size. Do not reach for String#count: its argument is a set of characters, like the ones in tr, so count("an") counts every a and every n, not the pair. scan does not count overlapping matches; a zero-width lookahead does.

count.rb
text = "banana bandana"

# scan returns every match, so .size counts them
p text.scan("an")
p text.scan("an").size

# count is NOT a substring count: it counts characters
p text.count("an")
p text.count("a")
p text.count("n")

# scan does not overlap: "aa" in "aaaa"
p "aaaa".scan("aa").size

# A lookahead counts overlapping matches
p "aaaa".scan(/(?=aa)/).size

# Case-insensitive count
p "Ruby ruby RUBY".scan(/ruby/i).size

Output

scan("an") finds the pair four times, but count("an") prints 10: the six a characters plus the four n characters, as the next two lines show. This is the usual wrong answer to "how many times does it appear". In "aaaa", scan finds aa twice because each match consumes its characters, while the lookahead /(?=aa)/ matches at every position followed by aa and finds 3. A regex with the i flag counts all three spellings of Ruby.

6When the string might be nil

A value from a hash, a regex capture or a method that found nothing is often nil, and nil has no include?: calling it raises NoMethodError. The safe navigation operator &. calls the method only when the receiver is not nil and returns nil otherwise, which an if treats as false. When you want a strict true or false, convert first with to_s, which turns nil into an empty string. Rails adds blank? and present? through ActiveSupport; plain Ruby does not have them.

nil_string.rb
name = nil

begin
  name.include?("x")
rescue NoMethodError => e
  puts "#{e.class}: #{e.message}"
end

# &. returns nil instead of calling the method on nil
p name&.include?("x")
puts "contains x" if name&.include?("x")

# to_s turns nil into "", giving true or false
p name.to_s.include?("x")

# A hash lookup that may miss
params = { q: "ruby strings" }
p params[:q]&.include?("ruby")
p params[:page]&.include?("2")
p params.fetch(:page, "").include?("2")

Output

The error reads undefined method 'include?' for nil. name&.include?("x") prints nil rather than false, and the if line prints nothing because nil is falsy. to_s and fetch with a default both give a real false, which matters when you store or print the result. The present key :q gives true through &. as usual.

7Which should you use?

MethodReturnsTakesBest for
s.include?(sub)true / falseA stringA plain substring anywhere: most checks
s.start_with?(a, b)true / falseStrings or a regexPrefixes, several at once
s.end_with?(a, b)true / falseStrings onlySuffixes such as file extensions
s.match?(/re/i)true / falseA regexPatterns and case-insensitive checks
s =~ /re/Index or nilA regexOlder code; when you also use $~
s.index(sub)Index or nilA string or a regexGetting where the substring is
s.scan(sub).sizeIntegerA string or a regexCounting occurrences
s.count(chars)Character countA set of charactersAvoid for substrings: use scan

Frequently asked questions

What is the Ruby version of Python's in or JavaScript's includes() for strings?

It is text.include?("sub"), which returns true or false. Ruby has no substring operator: "sub" in text is valid syntax, but it is pattern matching, and since text is a bare name it binds a new value to text and always matches.

Does Ruby have a startswith method?

Yes, start_with? and end_with?, both built into String. "report.csv".end_with?(".csv", ".tsv") checks several suffixes at once, and start_with? also takes a regex such as /v\d/. Rails code sometimes uses starts_with? and ends_with?, aliases added by ActiveSupport; plain Ruby has only the names without the s.

How do I check that a string does not contain a substring?

Negate include?: !text.include?("x"), or put it after unless: puts "clean" unless text.include?("x"). For a regex, text !~ /x/ is true when there is no match. Rails' exclude? is an ActiveSupport method and does not exist in plain Ruby.

How do I check if a string contains any of several substrings?

Loop over the candidates with any?: words.any? { |w| text.include?(w) }. Or build one regex with Regexp.union, which escapes each string for you: text.match?(Regexp.union("cpu", "disk")). Regexp.union("a.b", "c") gives /a\.b|c/.

What is the difference between match?, match and =~?

match? returns true or false and records nothing, so it is the fastest. =~ returns the start index or nil and stores the match in $~. match (no question mark) returns a MatchData object you can read captures from, or nil. Use match? for a yes or no and match when you need the matched text.

How do I check that a string contains only digits?

Use match? with \A and \z: "123".match?(/\A\d+\z/) is true. Avoid ^ and $: in Ruby they match at the start and end of each line, so "12\nab".match?(/^\d+$/) is true while the \A…\z version is false.

Run it yourself

Open any of these in the full Ruby editor to tweak, run and share.

Ruby playground