Labs ICT
โญ Pro Login

Strings

Working with text the Ruby way.

Strings

Ruby strings come in two flavors: single-quoted and double-quoted. Double-quoted strings support interpolation with #{}. Multi-line strings use heredocs. Strings are packed with useful methods like .length, .upcase, .downcase, .include?, .split, and .gsub. Use << to append to a string. Freeze a string to make it immutable.

# Single vs double quotes
single = 'Hello, World!'
double = "Hello, World!"

# Interpolation only works with double quotes
name = "Alice"
puts "Hello, #{name}!"  # => "Hello, Alice!"
puts 'Hello, #{name}!'  # => "Hello, #{name}!" โ€” literal text

# Multi-line strings with heredoc
message = <<~MSG
  This is a multi-line string.
  It preserves formatting.
  Very handy for templates.
MSG

# Useful string methods
greeting = "Hello, World!"
greeting.length       # => 13
greeting.upcase       # => "HELLO, WORLD!"
greeting.downcase     # => "hello, world!"
greeting.include?("World") # => true
greeting.split(", ")  # => ["Hello", "World!"]
greeting.gsub("World", "Ruby") # => "Hello, Ruby!"

# Appending with <<
name = "Hello"
name << ", World!"
puts name  # => "Hello, World!"

# Freeze for immutable strings
frozen_str = "immutable".freeze
# frozen_str << "!"  # => raises RuntimeError
Try it Yourself ->

๐Ÿงช Quick Quiz

How do you interpolate variables in strings?