Bird
0
0

How can you use a for loop in Ruby to create a hash where keys are numbers 1 to 3 and values are their squares?

hard📝 Application Q9 of 15
Ruby - Loops and Iteration
How can you use a for loop in Ruby to create a hash where keys are numbers 1 to 3 and values are their squares?
Ahash = {} for i in 1..3 do hash[i] = i * i end
Bhash = {} for i in 1..3 do hash[i] = i + i end
Chash = {} for i in 1..3 do hash[i] = i end
Dhash = {} for i in 1..3 do hash[i] = i / 2 end
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal

    Create a hash with keys 1 to 3 and values as squares of keys.
  2. Step 2: Check each option's assignment

    hash = {} for i in 1..3 do hash[i] = i * i end assigns i*i which is square. Others assign sums, keys, or division.
  3. Final Answer:

    hash = {} for i in 1..3 do hash[i] = i * i end -> Option A
  4. Quick Check:

    Assign squares as values in hash [OK]
Quick Trick: Use hash[key] = value inside for loop [OK]
Common Mistakes:
  • Assigning wrong value (sum, division)
  • Not initializing hash
  • Using wrong operators

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes