Ruby Strings
A string is a sequence of characters — names, messages, file contents, anything textual. Strings are one of Ruby's strongest areas: the String class has well over a hundred methods.
Single vs double quotes
food = "noodles"
puts "I like #{food}\tvery much"
puts 'I like #{food}\tvery much'I like noodles very much
I like #{food}\tvery much
Double quotes "..." |
Single quotes '...' |
|
|---|---|---|
Interpolation #{...} |
yes | no |
Escapes like \n, \t |
yes | only \' and \\ |
| Typical use | Most strings | Text that must be taken literally |
Interpolation
Anything inside #{ } is evaluated as Ruby code and converted to a string with to_s:
item = "lamp"
price = 24.5
qty = 3
puts "#{qty} x #{item} = #{price * qty} EUR"
puts "Upper: #{item.upcase}, length #{item.length}"3 x lamp = 73.5 EUR
Upper: LAMP, length 4
Any expression works inside the braces — a calculation, a method call, even a conditional. Interpolation is the preferred way to build strings in Ruby; it is clearer and faster than joining with +.
Concatenation and repetition
first = "Grace"
last = "Hopper"
full = first + " " + last
puts full
line = "-" * 12
puts line
log = +"" # an empty, unfrozen string
log << "start;"
log << "load;"
log.concat("done")
puts logGrace Hopper
------------
start;load;done
+ creates a new string, while << appends to the existing one (faster when building long text). + in front of a literal (+"") guarantees you get a mutable string.
Note:
"Age: " + 30raises aTypeError— Ruby does not convert numbers automatically. Use interpolation ("Age: #{30}") or30.to_s.
Indexing and slicing
Characters are numbered from 0. Negative indexes count from the end:
word = "Ruby rocks"
p word[0]
p word[-1]
p word[0, 4] # start, length
p word[5..] # from index 5 to the end
p word[0..2] # inclusive range
p word[100]
p word.chars.first(3)"R"
"s"
"Ruby"
"rocks"
"Rub"
nil
["R", "u", "b"]
Indexing past the end returns nil instead of raising an error.
Multi-line strings (heredocs)
For longer text use a heredoc. The squiggly form <<~ strips the common leading indentation, so the text can be indented with the code:
name = "Mira"
letter = <<~TEXT
Dear #{name},
thank you for your order.
See you soon!
TEXT
puts letterDear Mira,
thank you for your order.
See you soon!
TEXT is just a label — any capitalised word works, as long as the closing one matches.
Comparing strings
p "apple" == "apple"
p "Apple" == "apple"
p "Apple".casecmp?("apple")
p "apple" < "banana"
p "b" <=> "a"
p "".empty?true
false
true
true
1
true
<=> (the "spaceship" operator) returns -1, 0 or 1 and is what sorting uses behind the scenes.
Strings are mutable
Unlike in Python or Java, Ruby strings can be changed in place. Methods ending with ! modify the receiver; the version without ! returns a new string:
city = "oslo"
loud = city.upcase
puts city
puts loud
city.upcase!
puts cityoslo
OSLO
OSLO
Tip: Since Ruby 3.4, string literals in files without a magic comment are "chilled": changing them in place still works, but Ruby can warn about it when deprecation warnings are on. Future versions will freeze them by default, so prefer non-mutating methods or start with
+"..."/.dupwhen you need a mutable string.
Test yourself
What does puts 'Hi #{1 + 1}' print?
- Hi 2
- Hi #{1 + 1}
- Hi 1 + 1
- An error
What is "hello"[1, 3]?
- "hel"
- "ell"
- "el"
- "ello"
What is the difference between s.upcase and s.upcase!?
- None
upcase!modifiessin placeupcase!prints the resultupcase!also removes spaces