Skip to the workspace
Pebellslearn by building
Data Types  ›  Lesson

Strings and Symbols

Strings 12 minStrings hold text that people read or that changes, and double quotes allow interpolation, while symbols are immutable names, each a single shared object, used for keys and labels.

ruby / Strings and Symbols

Explore each scene at your own pace.

01 · The rule

The rule

Strings and Symbols

Strings hold text that people read or that changes, and double quotes allow interpolation, while symbols are immutable names, each a single shared object, used for keys and labels.

Compare mutable text with symbol identifiers and choose each deliberately.

Bean Cart's menu shows text to customers, like "Oat Milk Latte", and the code also needs short internal labels such as "which drink is this?". Ruby has a type for each job: strings for text that people read or that changes, and symbols for fixed names inside the program.

The rule

Strings are text you show; symbols are names you use.

A String is a sequence of characters in quotes. The kind of quote matters:

drink = "latte"
puts "One #{drink}, please"   # One latte, please
puts 'One #{drink}, please'   # One #{drink}, please

Double quotes allow interpolation with #{...} and escapes like \n for a newline. Single quotes print exactly what you typed. Many teams use double quotes by default, for consistency.

Strings are objects with many methods, and they can change:

drink.length          # => 5
drink.upcase          # => "LATTE"
drink + " to go"      # => "latte to go"   (new string)
drink << " to go"     # drink itself is now "latte to go"
"ab" * 3              # => "ababab"
drink.include?("go")  # => true

A Symbol starts with a colon: :latte, :mocha. It is a lightweight, immutable name. Every :latte in the program is the very same object, while two "latte" strings you write separately are two different objects:

:latte.equal?(:latte)     # => true  (same object)
"latte".equal?("latte")   # => false (two objects)
"latte" == "latte"        # => true  (same content)

Symbols are the usual choice for hash keys and option names, because they are fast to compare and never change:

MENU = { latte: 4.50, mocha: 5.00 }   # keys are :latte and :mocha

Converting between them is one method: :latte.to_s gives "latte", and "latte".to_sym gives :latte.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.