Bird
0
0

How can you use block parameters to swap keys and values in a hash?

hard📝 Application Q9 of 15
Ruby - Blocks, Procs, and Lambdas

How can you use block parameters to swap keys and values in a hash?

h = {a: 1, b: 2}
new_hash = {}
h.each do |key, value|
  new_hash[value] = key
end
puts new_hash

What is the output?

AError: wrong number of block parameters
B{1=>:a, 2=>:b}
C{a=>1, b=>2}
D{}
Step-by-Step Solution
Solution:
  1. Step 1: Understand hash iteration with two block parameters

    Each key and value are passed to the block as parameters.
  2. Step 2: Swap keys and values in new_hash

    Assign new_hash[value] = key to invert the hash.
  3. Final Answer:

    {1=>:a, 2=>:b} -> Option B
  4. Quick Check:

    Block parameters key,value used to swap hash pairs [OK]
Quick Trick: Use two block parameters to access key and value in hashes [OK]
Common Mistakes:
  • Using one block parameter for hash iteration
  • Confusing keys and values order
  • Expecting original hash output

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes