Strings and Symbols
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}, pleaseDouble 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") # => trueA 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 :mochaConverting between them is one method: :latte.to_s gives "latte", and "latte".to_sym gives :latte.
The shortcut
Ask "Will a person read it, or will it change?" If yes, use a String. If it is a fixed label that the program uses to pick something, such as a key, a status or an option, use a Symbol.
The customer's name
"Priya" is typed by a person and printed on the cup: String.
That last step is the classic trap: "latte" and :latte are different objects of different types, so a hash does not treat them as the same key.
Drills
Answer fast — trust the rule.
With drink = "tea", what does puts 'A #{drink}' print?
Which is best as a hash key for an order's status?
What does "latte".equal?("latte") return?
With MENU = { latte: 4.50 }, what does MENU["latte"] return?
After drink = "latte" and drink << "!", what is drink?
Remember
- Strings are text you show; symbols are names you use.
- Ask "will a person read it, or will it change?" Yes: String. Fixed label: Symbol.
- Trap:
"latte"and:latteare different hash keys, and single quotes skip interpolation.
