Bird
0
0

Given the hash grades = { john: 85, jane: 92, joe: 78 }, which Ruby code correctly uses each to print each student's name and grade in the format Student - Grade?

hard📝 Application Q8 of 15
Ruby - Loops and Iteration
Given the hash grades = { john: 85, jane: 92, joe: 78 }, which Ruby code correctly uses each to print each student's name and grade in the format Student - Grade?
Agrades.each { |grade| puts "#{grade[0]} - #{grade[1]}" }
Bgrades.each { |student| puts "#{student} - #{grades[student]}" }
Cgrades.each { |student, grade| puts "#{student.capitalize} - #{grade}" }
Dgrades.each { |student, grade| puts "#{grade} - #{student}" }
Step-by-Step Solution
Solution:
  1. Step 1: Understand hash iteration

    When iterating over a hash with each, two block variables represent the key and value.
  2. Step 2: Format output correctly

    Use string interpolation to print the capitalized student name and their grade separated by ' - '.
  3. Final Answer:

    grades.each { |student, grade| puts "#{student.capitalize} - #{grade}" } -> Option C
  4. Quick Check:

    Hash each yields key and value [OK]
Quick Trick: Hash each yields key and value [OK]
Common Mistakes:
MISTAKES
  • Using only one block variable for hash iteration
  • Swapping key and value in output
  • Not capitalizing the key when required

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes