Bird
0
0

Which of the following is the correct syntax to iterate over each key-value pair in a Ruby hash h?

easy📝 Syntax Q12 of 15
Ruby - Hashes
Which of the following is the correct syntax to iterate over each key-value pair in a Ruby hash h?
A<code>h.each(key, value) { puts key, value }</code>
B<code>h.each { |key, value| puts key + value }</code>
C<code>h.each do |key value| puts key, value end</code>
D<code>h.each { key, value -> puts key + value }</code>
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct block syntax for each

    The correct syntax uses curly braces or do-end with block parameters separated by a comma inside pipes: { |key, value| ... }.
  2. Step 2: Check each option

    h.each { |key, value| puts key + value } uses correct syntax with pipes and comma. Others have syntax errors or wrong block format.
  3. Final Answer:

    h.each { |key, value| puts key + value } -> Option B
  4. Quick Check:

    Correct block syntax = h.each { |key, value| puts key + value } [OK]
Quick Trick: Use pipes and commas inside block for key-value pairs [OK]
Common Mistakes:
  • Omitting pipes around block parameters
  • Missing comma between key and value
  • Using arrow syntax incorrectly in blocks

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes