Bird
0
0

Identify the error in this Ruby code:

medium📝 Debug Q6 of 15
Ruby - Hashes
Identify the error in this Ruby code:
h = {a: 1, b: 2}
h.each do |k|
  puts k
end
ANo error, code runs fine
Bh.each is not a valid method
CSyntax error due to missing parentheses
DBlock expects two variables but only one given
Step-by-Step Solution
Solution:
  1. Step 1: Check block parameters for each on hash

    each on a hash yields key and value, but with only one block parameter |k|, Ruby assigns an array [key, value] to k. No error occurs.
  2. Step 2: Verify code runs

    The code executes without syntax or runtime errors, printing [:a, 1] and [:b, 2].
  3. Final Answer:

    No error, code runs fine -> Option A
  4. Quick Check:

    Hash#each with |k| assigns [key, value] array to k [OK]
Quick Trick: Hash#each with single block arg receives [key, value] array, no error [OK]
Common Mistakes:
  • Thinking block arity causes error
  • Expecting syntax error
  • Using invalid method names

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes