0Pricing
Ruby Academy · Lesson

Searching and Replacing

gsub, sub, match.

Finding a Substring

The index method returns the position of the first match, or nil if not found. include? returns true or false.

text = "hello world"
puts text.index("world")
puts text.include?("world")

Replacing the First Match with sub

sub replaces only the first occurrence of a pattern with a new value.

text = "cat cat cat"
puts text.sub("cat", "dog")

All lessons in this course

  1. String Basics and Methods
  2. Interpolation and Formatting
  3. Searching and Replacing
  4. Splitting and Joining
← Back to Ruby Academy