0Pricing
Ruby Academy · Lesson

Substitution

gsub with patterns.

Replacing Text with sub

String#sub replaces the first match of a pattern with a replacement string. The original string is not changed; a new one is returned.

s = 'hello world'
puts(s.sub(/world/, 'Ruby'))
puts s

Replacing All with gsub

gsub means global substitution. It replaces every match, not just the first.

puts('a-b-c-d'.gsub(/-/, '_'))
puts('one two two'.gsub(/two/, 'three'))

All lessons in this course

  1. Regex Literals
  2. Matching and Capturing
  3. Substitution
  4. Named Groups and Anchors
← Back to Ruby Academy