Strings in Ruby
Mutable text with rich methods and encoding support.
Basics and interpolation
Double quotes interpolate; single quotes do not (except \ and \').
name = "Ruby"
"Hello, #{name}!" # => "Hello, Ruby!"
'Hello, #{name}!' # => "Hello, \\#{name}!"
Encodings and length
Ruby strings are encoding‑aware (UTF‑8 by default). length counts characters (codepoints); bytesize counts bytes.
"résumé".encoding # => #<Encoding:UTF-8>
"résumé".length # => 6
"résumé".bytesize # => 8
Common operations
" hi ".strip # => "hi"
"a,b,c".split(",") # => ["a","b","c"]
"test".gsub("t", "T") # => "TesT"
"go" * 3 # => "gogogo"
"path/to" + "/file" # concatenation
["a","b"].join("-") # => "a-b"
Mutation and freezing
Strings are mutable; bang methods modify in place. Freeze to make immutable.
s = "hello"
s.upcase! # => "HELLO" (s mutated)
s << "!" # append
s.freeze
# s << "!" # would raise FrozenError
Substrings and indexing
s = "hello"
s[0] # => "h"
s[1,3] # => "ell"
s[0..1] # => "he"
Regex integration
match, scan, sub/gsub integrate with regular expressions.
"a1 b22".scan(/\d+/) # => ["1", "22"]
"color".sub(/or/, "our") # => "colour"
"a1 b2".gsub(/\d+/) { |d| (d.to_i * 2).to_s } # => "a2 b4"
Heredoc
Convenient multi‑line literals; squiggly heredoc strips indentation.
message = <<~TEXT
Hello,
world.
TEXT
Performance notes
- Prefer string interpolation (
"#{x}") over concatenation in loops - Use
StringIOfor building large strings incrementally
Summary
- Use double quotes for interpolation, single for literals
- Strings are mutable by default; freeze when sharing or for safety
- Understand encodings when slicing and measuring