Strings
| Double vs single quotes | |
| Interpolation #{} | |
| Heredocs | |
| Handy methods |
Double vs single quotes
Strings can sit in double or single quotes, and for plain text both behave the same. Double quotes additionally process escape sequences such as newline, while single quotes keep almost everything literally.
a = "hi"
b = 'hi'
puts "a\nb" # prints a, then b on a new line
puts 'a\nb' # prints a\nb literally
Interpolation #{}
Inside double quotes you can embed any expression with a hash mark and curly braces. Ruby runs the code inside the braces and pastes the result into the string.
name = "Ada"
puts "Hello, #{name}" # prints Hello, Ada
puts "2 + 2 = #{2 + 2}" # prints 2 + 2 = 4
Interpolation works only in double quotes. In single quotes the same braces stay untouched, which is a classic beginner surprise.
Heredocs
Long multi-line text is easier to read as a heredoc than as many quoted lines. Open with two angle signs and a label, write any lines you want, then close with the same label on its own line.
text = <<~TEXT
Hello,
Ruby.
TEXT
puts text
Hello,
Ruby.
Handy methods
Strings come with many small helpers. length counts characters, upcase builds a loud copy, strip trims spaces on both sides, and split cuts a string into an array of pieces.
"Ada".length # => 3
"ada".upcase # => "ADA"
" Ada ".strip # => "Ada"
"a,b".split(",") # => ["a", "b"]
Next: Symbols
Article author: Arthur Isaev