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 Q15 of 15
Ruby - Loops and Iteration
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.capitalize}: #{score}" }
Bscores.each { |score, name| puts "#{name}: #{score}" }
Cscores.each { |name| puts "#{name}: #{score}" }
Dscores.each { |name, score| puts "#{score.capitalize}: #{name}" }
Step-by-Step Solution
Solution:
  1. Step 1: Understand each on a hash

    When using each on a hash, the block receives two variables: key and value.
  2. Step 2: Match variables and format output

    The key is the name (symbol), value is the score. Use name.capitalize to print the name nicely.
  3. Final Answer:

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

    Hash each uses key, value pairs [OK]
Quick Trick: Hash each block gets two vars: key and value [OK]
Common Mistakes:
MISTAKES
  • Swapping key and value variables
  • Using only one block variable for hash
  • Trying to capitalize a number

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes