0
0
Rubyprogramming~10 mins

Hash creation with symbols and strings in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Hash creation with symbols and strings
Start
Define key-value pairs
Use symbols or strings as keys
Create hash object
Access or modify hash
End
This flow shows how to create a hash in Ruby using symbols or strings as keys, then access or modify it.
Execution Sample
Ruby
person = { :name => "Alice", "age" => 30 }
puts person[:name]
puts person["age"]
Creates a hash with a symbol key and a string key, then prints their values.
Execution Table
StepActionEvaluationResult
1Create hash with keys :name and "age"person = { :name => "Alice", "age" => 30 }{:name=>"Alice", "age"=>30}
2Access value with symbol key :nameperson[:name]"Alice"
3Print value for :nameputs person[:name]Alice
4Access value with string key "age"person["age"]30
5Print value for "age"puts person["age"]30
6End of program
💡 Program ends after printing both values.
Variable Tracker
VariableStartAfter Step 1After Step 6
personundefined{:name=>"Alice", "age"=>30}{:name=>"Alice", "age"=>30}
Key Moments - 2 Insights
Why do we use :name with a colon but "age" in quotes as keys?
In Ruby, symbols like :name are lightweight and often used as keys, while strings like "age" are also valid keys but different objects. The execution_table rows 1-4 show both types used as keys.
Can we access a symbol key using a string or vice versa?
No, symbol keys and string keys are different. For example, person[:name] works but person["name"] returns nil. This is shown in execution_table row 2 and 4 where keys are accessed exactly as defined.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of person[:name] at step 2?
A"Alice"
B30
Cnil
D"age"
💡 Hint
Check the 'Evaluation' and 'Result' columns at step 2 in execution_table.
At which step does the program print the value 30?
AStep 3
BStep 4
CStep 5
DStep 6
💡 Hint
Look for 'puts 30' in the 'Evaluation' column in execution_table.
If we try person["name"] instead of person[:name], what would happen?
AIt prints "Alice"
BIt returns nil
CIt prints 30
DIt causes an error
💡 Hint
Refer to key_moments explanation about symbol vs string keys.
Concept Snapshot
Hash creation in Ruby:
Use symbols (:key) or strings ("key") as keys.
Example: { :name => "Alice", "age" => 30 }
Access with exact key type: person[:name], person["age"]
Symbols are efficient keys; strings are also valid.
Keys of different types are not interchangeable.
Full Transcript
This example shows how to create a Ruby hash with keys as symbols and strings. The hash person has two keys: :name (a symbol) and "age" (a string). We access values by using the exact key type. The program prints "Alice" for person[:name] and 30 for person["age"]. Symbols and strings are different keys, so person["name"] would not find the value. This is important to remember when working with hashes in Ruby.