Bird
0
0

Given a hash scores = { 'Alice' => 10, 'Bob' => 15, 'Carol' => 12 }, how can you use each to print each name and score in the format Name: Score?

hard📝 Application Q8 of 15
Ruby - Enumerable and Collection Processing
Given a hash scores = { 'Alice' => 10, 'Bob' => 15, 'Carol' => 12 }, how can you use each to print each name and score in the format Name: Score?
Ascores.each { |name, score| puts "#{name}: #{score}" }
Bscores.each { |score| puts "#{name}: #{score}" }
Cscores.each do |name| puts "#{name}: #{score}" end
Dscores.each { |name| puts name }
Step-by-Step Solution
Solution:
  1. Step 1: Understand hash iteration with each

    When iterating a hash, each passes two block variables: key and value.
  2. Step 2: Use both variables to print formatted string

    scores.each { |name, score| puts "#{name}: #{score}" } correctly uses two variables and prints them in the required format.
  3. Final Answer:

    scores.each { |name, score| puts "#{name}: #{score}" } -> Option A
  4. Quick Check:

    Hash each uses two block variables [OK]
Quick Trick: Hash each passes key and value to block variables [OK]
Common Mistakes:
  • Using one block variable for hash
  • Referencing undefined variables
  • Incorrect string interpolation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes