0
0
Rubyprogramming~5 mins

Hash creation with symbols and strings in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a hash in Ruby?
A hash is a collection of key-value pairs, like a dictionary, where you can look up a value using its key.
Click to reveal answer
beginner
How do you create a hash with symbol keys in Ruby?
You can create it using curly braces and symbol keys with colons, like: { name: "Alice", age: 30 }.
Click to reveal answer
beginner
How do you create a hash with string keys in Ruby?
Use curly braces with strings as keys and hash rockets, like: { "name" => "Alice", "age" => 30 }.
Click to reveal answer
intermediate
What is the difference between symbol keys and string keys in Ruby hashes?
Symbol keys are immutable and often faster, while string keys are mutable. Symbols are written without quotes and strings with quotes.
Click to reveal answer
intermediate
Show an example of a Ruby hash mixing symbol and string keys.
Example: { name: "Alice", "age" => 30 }. You can mix keys but be careful when accessing values.
Click to reveal answer
Which of these is a valid Ruby hash with symbol keys?
A{ name: "Bob", city: "NY" }
B{ "name" => "Bob", "city" => "NY" }
C[ name: "Bob", city: "NY" ]
D( name: "Bob", city: "NY" )
How do you access the value for key :name in hash { name: "Eve" }?
Ahash["name"]
Bhash[:name]
Chash.name
Dhash->name
Which symbol key is equivalent to the string key "age" in a Ruby hash?
A:age
B"age"
Cage
Dage:
What happens if you mix symbol and string keys in a Ruby hash?
AThey are treated as the same key
BThe string key overrides the symbol key
CThey are treated as different keys
DRuby throws an error
Which syntax creates a hash with string keys?
A{ color: "red", size: "M" }
B( color: "red", size: "M" )
C[ "color" => "red", "size" => "M" ]
D{ "color" => "red", "size" => "M" }
Explain how to create a Ruby hash using symbol keys and how to access its values.
Think about keys without quotes and how you get values.
You got /3 concepts.
    Describe the difference between using string keys and symbol keys in Ruby hashes.
    Consider how keys look and behave.
    You got /4 concepts.