Bird
Raised Fist0
Rubyprogramming~10 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. Which of the following is a valid way to create a Ruby hash with symbol keys?
easy
A. { name => "Alice", age => 30 }
B. { "name": "Alice", "age": 30 }
C. { :name => "Alice", "age": 30 }
D. { name: "Alice", age: 30 }

Solution

  1. Step 1: Understand symbol key syntax

    In Ruby, symbol keys can be written as name: value without the rocket (=>) syntax.
  2. Step 2: Check each option's syntax

    { name: "Alice", age: 30 } uses symbol keys with colon syntax correctly. { "name": "Alice", "age": 30 } uses string keys with colon, which is invalid. { :name => "Alice", "age": 30 } uses rocket syntax for the symbol key correctly but attempts colon syntax after a string key, which is invalid. { name => "Alice", age => 30 } uses bare words without colon or rocket, which is invalid.
  3. Final Answer:

    { name: "Alice", age: 30 } -> Option D
  4. Quick Check:

    Symbol keys use colon syntax = { name: "Alice", age: 30 } [OK]
Hint: Symbol keys use colon after name, not quotes or bare words [OK]
Common Mistakes:
  • Using quotes around symbol keys with colon syntax
  • Omitting colon or rocket for keys
  • Mixing string and symbol keys without proper syntax
2. Which of the following hash definitions will cause a syntax error in Ruby?
easy
A. { name => "Bob", age => 25 }
B. { :name => "Bob", :age => 25 }
C. { "name" => "Bob", "age" => 25 }
D. { name: "Bob", age: 25 }

Solution

  1. Step 1: Review valid key syntax

    Symbol keys can be written as :name => or name:. String keys must be quoted and use rocket syntax.
  2. Step 2: Identify invalid syntax

    { name => "Bob", age => 25 } uses bare words as keys without colon or rocket, which is invalid and causes syntax error.
  3. Final Answer:

    SyntaxError -> Option A
  4. Quick Check:

    Bare words as keys need colon or rocket [OK]
Hint: Keys must be symbols with colon or strings with quotes and rocket [OK]
Common Mistakes:
  • Using bare words as keys without colon or rocket
  • Mixing string keys without quotes
  • Confusing colon placement for symbols
3. What is the output of the following Ruby code?
person = { name: "Carol", "age" => 28 }
puts person[:name]
puts person["age"]
medium
A. Carol 28
B. Carol
C. 28
D. nil nil

Solution

  1. Step 1: Understand hash keys and access

    The hash has a symbol key :name and a string key "age". Accessing with matching key types returns values.
  2. Step 2: Evaluate each puts statement

    person[:name] returns "Carol". person["age"] returns 28. Both print on separate lines.
  3. Final Answer:

    Carol 28 -> Option A
  4. Quick Check:

    Match key types to get values = Carol 28 [OK]
Hint: Use matching symbol or string keys to access hash values [OK]
Common Mistakes:
  • Accessing string key with symbol or vice versa
  • Expecting mixed keys to be interchangeable
  • Forgetting keys are type-sensitive
4. Identify the error in this Ruby hash creation:
data = { :city => "Paris", country: "France", "population" => 2148327, state } 
medium
A. Hash keys cannot mix symbols and strings
B. Incorrect symbol syntax for :city
C. Missing value for key 'state'
D. String keys must use colon syntax

Solution

  1. Step 1: Check each key-value pair

    Keys :city, country, and "population" have values. The key 'state' is written without a value, which is invalid.
  2. Step 2: Identify syntax error

    Every key in a hash must have a corresponding value. Missing value for 'state' causes syntax error.
  3. Final Answer:

    Missing value for key 'state' -> Option C
  4. Quick Check:

    All keys need values in hash = Missing value for key 'state' [OK]
Hint: Every key must have a value; check for missing pairs [OK]
Common Mistakes:
  • Leaving keys without values
  • Confusing symbol and string key syntax
  • Assuming mixed keys cause errors
5. Given the array arr = [["name", "Dave"], [:age, 40], ["city", "NY"]], which code correctly converts it into a hash with symbol keys where possible?
hard
A. hash = arr.to_h
B. hash = arr.map { |k, v| [k.to_sym, v] }.to_h
C. hash = arr.map { |k, v| [k, v] }.to_h
D. hash = arr.map { |k, v| [k.to_s, v] }.to_h

Solution

  1. Step 1: Understand the array structure

    The array has pairs with keys as strings or symbols. We want all keys as symbols where possible.
  2. Step 2: Convert keys to symbols

    hash = arr.map { |k, v| [k.to_sym, v] }.to_h converts each key to symbol using k.to_sym before creating the hash, ensuring keys are symbols.
  3. Step 3: Check other options

    hash = arr.to_h keeps keys as is (mixed). hash = arr.map { |k, v| [k, v] }.to_h keeps keys as is without conversion. hash = arr.map { |k, v| [k.to_s, v] }.to_h converts all keys to strings, not symbols.
  4. Final Answer:

    hash = arr.map { |k, v| [k.to_sym, v] }.to_h -> Option B
  5. Quick Check:

    Use to_sym on keys to get symbol keys [OK]
Hint: Use map with to_sym on keys to get symbol keys [OK]
Common Mistakes:
  • Not converting string keys to symbols
  • Using to_s instead of to_sym
  • Assuming to_h converts keys automatically
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard