TExcelTAD
Home › Ruby › Ruby Strings

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

ruby · try it yourself
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:

ruby · try it yourself
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

ruby · try it yourself
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 log
Grace 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: " + 30 raises a TypeError — Ruby does not convert numbers automatically. Use interpolation ("Age: #{30}") or 30.to_s.

Indexing and slicing

Characters are numbered from 0. Negative indexes count from the end:

ruby · try it yourself
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:

ruby · try it yourself
name = "Mira"
letter = <<~TEXT
  Dear #{name},
    thank you for your order.
  See you soon!
TEXT
puts letter
Dear 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

ruby · try it yourself
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:

ruby · try it yourself
city = "oslo"
loud = city.upcase
puts city
puts loud

city.upcase!
puts city
oslo
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 +"..." / .dup when you need a mutable string.

Test yourself

What does puts 'Hi #{1 + 1}' print?

  1. Hi 2
  2. Hi #{1 + 1}
  3. Hi 1 + 1
  4. An error

What is "hello"[1, 3]?

  1. "hel"
  2. "ell"
  3. "el"
  4. "ello"

What is the difference between s.upcase and s.upcase!?

  1. None
  2. upcase! modifies s in place
  3. upcase! prints the result
  4. upcase! also removes spaces