Skip to content

Ruby Strings — Interpolation gsub split freeze and Encoding Explained

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about Ruby Strings. We cover key concepts, practical examples, and best practices to help you master this topic.

Ruby strings support interpolation with #{} for embedding expressions, gsub for pattern-based substitution, split for tokenization, freeze for immutability, and multiple encoding formats including UTF-8.

What You'll Learn

  • String creation, interpolation, and concatenation
  • Pattern substitution with gsub and sub
  • Splitting and joining strings
  • Freezing strings for performance
  • Encoding and character sets

Why It Matters

String manipulation is the most common task in programming. Durga Antivirus Pro processes file paths, log entries, and threat signatures as strings. DodaZIP parses filenames, metadata, and compression headers. Doda Browser handles URLs, HTML, and user input. Mastering Ruby strings means mastering text processing.

Real-World Use

A Rails application processes form input, generates HTML, validates emails, and formats output — all string operations. A data pipeline transforms CSV rows, JSON payloads, and log entries. Every Ruby program touches strings constantly.

flowchart LR
    A["Strings"] --> B["Creation"]
    B --> C["Manipulation"]
    C --> D["Patterns"]
    D --> E["Encoding"]
    A:::current --> B
    style A fill:#2563eb,stroke:#2563eb,color:#fff
    style B fill:#dbeafe,stroke:#2563eb,color:#1e40af
    style C fill:#dbeafe,stroke:#2563eb,color:#1e40af
    style D fill:#dbeafe,stroke:#2563eb,color:#1e40af
    style E fill:#f1f5f9,stroke:#94a3b8,color:#64748b

Creating Strings

single = 'Hello'
double = "Hello"
name = "Alice"
puts "Hello, #{name}"   # Hello, Alice
puts 'Hello, #{name}'   # Hello, #{name}
puts "Line1\nLine2"
sql = <<~SQL
  SELECT * FROM users WHERE active = true
SQL
puts %q(no interpolation)
puts %Q(with #{name})

String Interpolation

name = "Alice"
age = 25
puts "#{name} is #{age} years old"
puts "2 + 2 = #{2 + 2}"
puts "Uppercase: #{name.upcase}"
@count = 5
puts "Count: #{@count}"

Concatenation and Append

hello = "Hello"
world = "World"
puts hello + ", " + world
hello << ", " << world
puts hello
puts "Ha" * 3

Substitution: gsub and sub

text = "The quick brown fox jumps over the lazy dog"
puts text.sub("quick", "slow")
puts text.gsub("the", "A")
puts text.gsub(/[aeiou]/, "*")
puts text.gsub(/\b\w+\b/) { |word| word.length.to_s }
text2 = "hello world"
text2.gsub!("o", "0")
puts text2

Splitting and Joining

csv = "apple,banana,cherry"
fruits = csv.split(",")
puts fruits.inspect
data = "a,b,c,d,e"
puts data.split(",", 3).inspect
words = "one  two   three".split
puts words.inspect
puts fruits.join(" | ")
puts [1, 2, 3].join(", ")

Freezing Strings

text = "immutable"
text.freeze
puts text.frozen?

String Comparison

puts "abc" == "abc"
puts "abc".casecmp("ABC")
puts "abc" <=> "def"

Case Conversion

text = "Hello World"
puts text.upcase
puts text.downcase
puts text.capitalize
puts text.swapcase

Strip and Padding

text = "  hello  "
puts text.strip
puts "hello".center(11)
puts "hello".ljust(10, "-")
puts "hello".rjust(10, "-")

String Query Methods

text = "Hello, Ruby World"
puts text.length
puts text.empty?
puts text.include?("Ruby")
puts text.start_with?("Hello")
puts text.end_with?("World")

Character Access

text = "Ruby"
puts text[0]
puts text[-1]
puts text[0, 3]
puts text[0..2]

Encoding

text = "Hello"
puts text.encoding
text.force_encoding("ISO-8859-1")
puts text.valid_encoding?
utf8 = "Hello".encode("UTF-8")

Formatting

puts format("Pi is %.2f", Math::PI)
puts "Pi is %.2f" % Math::PI
puts "%s has %d apples" % ["Alice", 5]
puts "%<name>s has %<count>d apples" % { name: "Bob", count: 3 }

Common Mistakes

1. Single Quotes Don't Interpolate

name = "Alice"
puts 'Hello, #{name}'  # Literal string!
puts "Hello, #{name}"

2. gsub! Returns nil When No Change

text = "hello"
result = text.gsub!("z", "x")
puts result.nil?

3. Using + in Loops

result = ""
1000.times { |i| result += "item #{i}, " }

4. String Mutation Surprises

a = "hello"
b = a
a.upcase!
puts b

5. Not Handling Encoding Errors

text.encode("ASCII", invalid: :replace, undef: :replace)

6. Mutable Strings

a = "hello"
b = a
a << " world"
puts b

Practice Questions

1. What's the difference between single and double quotes? Single quotes treat content literally. Double quotes support interpolation and escape sequences.

2. What do gsub and sub do? sub replaces the first occurrence. gsub replaces all occurrences. Both accept strings or regex patterns.

3. How do you make a string immutable? Call .freeze on it.

4. What does split return? An array of substrings divided by a delimiter.

Challenge: Write a method that takes a sentence and returns a hash with word frequencies, sorted by frequency descending.

Solution
def word_frequency(sentence)
  sentence.downcase
          .gsub(/[^a-z\s]/, "")
          .split
          .each_with_object(Hash.new(0)) { |word, h| h[word] += 1 }
          .sort_by { |_, count| -count }
          .to_h
end

sentence = "Ruby is fun, Ruby is powerful, and Ruby is elegant!"
result = word_frequency(sentence)
puts result.inspect

FAQ

{{< faq question="What is the difference between String#<< and String#+?" >}} << modifies the string in place. + creates a new string. Use << for performance. {{< /faq >}}

{{< faq question="How do I check if a string contains a substring?" >}} Use .include?("substring") or .match?(/regex/). {{< /faq >}}

{{< faq question="What is the frozen_string_literal magic comment?" >}} # frozen_string_literal: true makes all string literals frozen by default. {{< /faq >}}

{{< faq question="How does Ruby handle encodings?" >}} Ruby 3.x defaults to UTF-8. Strings track their encoding internally. {{< /faq >}}

{{< faq question="What's the difference between chomp and chop?" >}} chomp removes trailing newline. chop removes the last character. {{< /faq >}}

Try It Yourself

text = "  The Quick Brown Fox Jumps Over The Lazy Dog  "
puts "Original: #{text}"
puts "Strip: '#{text.strip}'"
puts "Length: #{text.length}"
puts "Word count: #{text.split.size}"
puts "gsub vowels: #{text.gsub(/[aeiou]/i, '*')}"
puts "Reverse: #{text.reverse}"

What's Next

Now learn about regular expressions for powerful pattern matching.

Topic Description Link
Ruby Regex =~, match, scan, named captures {{< ref "18-regex" >}}
Ruby File I/O File, IO, Dir, CSV, JSON {{< ref "19-file-io" >}}

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro