String#sub

str.sub(pattern, replacement) -> string
Returns: string · Updated March 13, 2026 · String Methods
strings substitution regex pattern-matching

String#sub replaces only the first occurrence of a pattern in a string. It returns a new string with just the first match replaced by the replacement. Use this when you only need to replace the first occurrence.

Syntax

str.sub(pattern, replacement)
str.sub(pattern) { |match| block }

Parameters

ParameterTypeDefaultDescription
patternString or RegexpThe substring or pattern to find and replace
replacementString, Hash, or nilThe replacement text, hash of substitutions, or nil when using a block

Examples

Basic string replacement

text = "hello world"
text.sub("world", "Ruby")
# => "hello Ruby"

Replacing only first occurrence

text = "hello world hello"
text.sub("hello", "goodbye")
# => "goodbye world hello"

Note the difference from gsub: only the first “hello” is replaced.

Using regex patterns

phone = "(555) 123-4567"
phone.sub(/\(\d{3}\)\s*/, "")
# => "123-4567" (only first pattern removed if multiple)

text = "one two three"
text.sub(/\w+/) { |word| word.upcase }
# => "ONE two three" (only first word transformed)

Using a hash for replacement

replacements = { "cat" => "dog", "run" => "walk" }
"cat run".sub(/cat|run/, replacements)
# => "dog run" (only first match replaced)

Working with capture groups

"first last".sub(/(\w+) (\w+)/, '\2, \1')
# => "last, first"

"hello".sub(/[aeiou]/) { |v| v.upcase }
# => "hEllo" (only first vowel replaced)

Common Patterns

  • Replace first occurrence: text.sub("old", "new")
  • Remove first character: text.sub(/^./, "")
  • First letter capitalization: text.sub(/[a-z]/) { |c| c.upcase }
  • Pattern-based first replacement: text.sub(/\s+/, " ")

Errors

  • No pattern given: Raises ArgumentError if neither pattern nor block is provided.
  • String interpolation in replacement: Remember to escape \1, \2 when using double-quoted strings, or use single quotes.

Performance Notes

sub is slightly faster than gsub when you only need to replace the first occurrence, as it stops after the first match.

See Also