Bird
0
0

Given the following code, what will be the output?

hard📝 Application Q15 of 15
Ruby - Variables and Data Types

Given the following code, what will be the output?

hash = { apple: 1, banana: 2 }
key = :apple
hash[key] = 3
puts hash[:apple]

Consider the immutability and identity of symbols in your answer.

A3
B1
Cnil
DKeyError
Step-by-Step Solution
Solution:
  1. Step 1: Understand symbol keys in hash

    Symbols used as keys are immutable and unique, so :apple and key (which is :apple) refer to the same key.
  2. Step 2: Update hash value for :apple

    Assigning hash[key] = 3 updates the value for the :apple key from 1 to 3.
  3. Step 3: Output the updated value

    puts hash[:apple] prints the updated value 3.
  4. Final Answer:

    3 -> Option A
  5. Quick Check:

    Symbol keys are unique, so value updates correctly [OK]
Quick Trick: Symbol keys are unique; updating key changes value [OK]
Common Mistakes:
  • Thinking key is different because of variable
  • Expecting original value 1 instead of updated 3
  • Confusing symbols with strings as keys
  • Assuming symbols can be duplicated in hash keys

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes