Symbols as Hash Keys
Part of the Fundamentals section of Coddy's Ruby journey — lesson 78 of 88.
So far, you've been using strings as hash keys with the hash rocket syntax. However, Ruby developers commonly use symbols as keys instead, which offers a cleaner and more efficient approach.
Remember symbols from earlier? They're lightweight, immutable identifiers that start with a colon. When using symbols as keys, Ruby provides a special shorthand syntax:
person = {name: "Alice", age: 25, city: "Paris"}
puts person # Outputs: {:name=>"Alice", :age=>25, :city=>"Paris"}Notice how name: replaces :name =>. This shorthand only works when the key is a symbol. To access values, use the symbol with square brackets:
person = {name: "Alice", age: 25}
puts person[:name] # Outputs: Alice
puts person[:age] # Outputs: 25Adding and modifying entries works the same way:
person = {name: "Alice"}
person[:city] = "Paris"
person[:name] = "Bob"
puts person # Outputs: {:name=>"Bob", :city=>"Paris"}Symbols are preferred as hash keys because they're faster to compare than strings and use less memory. You'll see this pattern throughout Ruby code, so it's worth getting comfortable with it.
Challenge
EasyRead three lines of input:
- A car brand (string)
- A model name (string)
- A year (integer)
Create a hash called car using the symbol shorthand syntax (e.g., key: value) with the following key-value pairs:
:brandmapped to the car brand:modelmapped to the model name:yearmapped to the year (as an integer)
Then perform these operations:
- Print the value of the
:modelkey - Add a new key
:colorwith the value"black" - Update the
:yearkey by adding 1 to its current value - Print the final hash
For example, if the inputs are Toyota, Camry, and 2020, the output should be:
Camry
{:brand=>"Toyota", :model=>"Camry", :year=>2021, :color=>"black"}If the inputs are Honda, Civic, and 2018, the output should be:
Civic
{:brand=>"Honda", :model=>"Civic", :year=>2019, :color=>"black"}If the inputs are Ford, Mustang, and 2023, the output should be:
Mustang
{:brand=>"Ford", :model=>"Mustang", :year=>2024, :color=>"black"}Cheat sheet
Ruby provides a shorthand syntax for creating hashes with symbol keys:
person = {name: "Alice", age: 25, city: "Paris"}This is equivalent to using the hash rocket syntax with symbols:
person = {:name => "Alice", :age => 25, :city => "Paris"}To access values from a hash with symbol keys, use square brackets with the symbol:
puts person[:name] # Outputs: Alice
puts person[:age] # Outputs: 25Adding and modifying entries works the same way as with string keys:
person[:city] = "Paris" # Add new key-value pair
person[:name] = "Bob" # Modify existing valueSymbols are preferred as hash keys because they're faster to compare than strings and use less memory.
Try it yourself
# Read input
brand = gets.chomp
model = gets.chomp
year = gets.chomp.to_i
# TODO: Write your code below
# 1. Create a hash called 'car' using symbol shorthand syntax with :brand, :model, and :year keys
# 2. Print the value of the :model key
# 3. Add a new key :color with the value "black"
# 4. Update the :year key by adding 1 to its current value
# 5. Print the final hashThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input11Arrays
Creating ArraysAccessing Array ElementsModifying ArraysArray MethodsRecap - Product ArrayRecap - Reversed ArrayArray Shortcuts14Hashes
Creating HashesAccessing Hash ElementsModifying HashesHash MethodsRecap - Product HashSymbols as Hash Keys3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or False