♦️ String Interpolation: More Than Just #{variable}
Ruby's string interpolation looks simple."Hello, #{name}" and you're done, right? Wrong. You can shove entire expressions, method chains, and ternary operators inside those curly braces. Plus Ruby has a % operator for sprintf that'll make your formatted output sing.
Part 1: Basic Interpolation
Ruby uses#{} inside double-quoted strings (like Perl's $var in qq~~):
name = "Mike" puts "Hello, #{name}" # => Hello, Mike puts %Q~Hello, #{name}~ # Same - %Q supports interpolation
Part 2: Expressions Inside Interpolation
Any Ruby expression works inside#{}:
"Count: #{count}" # variable "Result: #{x > 0 ? 'yes' : 'no'}" # ternary "Today: #{Time.now.strftime('%Y-%m-%d')}" # method call "Debug: #{obj.inspect}" # inspect for debugging "Sum: #{[1, 2, 3].sum}" # any expression "Upper: #{"hello".upcase}" # string method
Part 3: Where Interpolation Works (and Doesn't)
Interpolation works in:- Double-quoted strings:
"#{var}" %Q~~strings:%Q~#{var}~%W~~word arrays:%W~#{var} other~- Heredocs (double-quoted, the default):
<<~END ... #{var} ... END - Backticks/
%x~~:`echo #{var}` - Regex:
%r~#{pattern}~
Interpolation does NOT work in:
- Single-quoted strings:
'#{var}'(stays literal) %q~~strings:%q~#{var}~(stays literal)%w~~word arrays:%w~#{var}~(stays literal)- Single-quoted heredocs:
<<~'END'
Same rule as Perl: double-quote means interpolation, single-quote means literal.
Part 4: The sprintf Shortcut
The% operator on strings is a shortcut for sprintf:
# Single value "%04d" % 42 # => "0042" "%.2f" % Math::PI # => "3.14" "%s files" % count # => "5 files" # Multiple values (use array) "%s: %d" % ["count", 5] # => "count: 5" "%-10s %5d %8.2f" % ["item", 42, 3.14] # => "item 42 3.14" # Perl equivalent: # sprintf("%04d", 42) # sprintf("%s: %d", "count", 5)
Part 5: printf for Direct Output
# Like Perl's printf - prints directly instead of returning string printf "%6d %s\n", count, ip printf "%-20s %s\n", filename, status # Kernel#format is an alias for sprintf (returns string) msg = format("Found %d errors in %s", count, filename)
Part 6: Format Specifiers Quick Reference
| Specifier | Meaning | Example |
|---|---|---|
%s |
String | "hello" |
%d |
Integer | 42 |
%f |
Float | 3.14 |
%e |
Scientific | 3.14e+00 |
%x |
Hex | 2a |
%o |
Octal | 52 |
%b |
Binary | 101010 |
%% |
Literal % |
% |
%10sright-aligns in 10 chars%-10sleft-aligns in 10 chars%04dzero-pads to 4 digits%.2fgives 2 decimal places
The % operator is one of those things you'll use constantly once you know it exists. It's cleaner than sprintf for simple cases and way more readable than string concatenation.
Created By: Wildcard Wizard. Copyright 2026