Bird
0
0

Fix the error in this Ruby code snippet:

medium📝 Debug Q7 of 15
Ruby - Hashes
Fix the error in this Ruby code snippet:
h = {a: 1, b: 2}
h.values.each do |k, v|
  puts k
end
AUse h.each instead of h.values.each
BChange h.values to h.keys
CAdd parentheses to each method call
DChange block to |v| instead of |k, v|
Step-by-Step Solution
Solution:
  1. Step 1: Understand what h.values returns

    h.values returns an array of values only, so each yields one element per iteration.
  2. Step 2: Check block parameters

    The block expects two variables |k, v|, but only one value is yielded, causing an error.
  3. Step 3: Fix the block parameters

    Change block to accept one variable |v| to match the single yielded value.
  4. Final Answer:

    Change block to |v| instead of |k, v| -> Option D
  5. Quick Check:

    Block vars must match yielded values count [OK]
Quick Trick: Block vars count must match each yields [OK]
Common Mistakes:
MISTAKES
  • Using two block vars for single yielded value
  • Changing method instead of block
  • Adding unnecessary parentheses

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes