Bird
0
0

Identify the problem in this Ruby method:

medium📝 Debug Q7 of 15
Ruby - Methods
Identify the problem in this Ruby method:
def multiply_all(*values)
  product = 1
  values.each do |v|
    product *= v
  end
  product
end

puts multiply_all(2, 3, '4')
AThe method should use + instead of * for multiplication
BThe method should initialize product to 0 instead of 1
CThe method should use map instead of each
DThe method does not handle string arguments causing a TypeError
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the method behavior

    The method multiplies all arguments starting with product = 1.
  2. Step 2: Check argument types

    Passing a string '4' will cause a TypeError when multiplying an Integer by a String.
  3. Step 3: Review options

    The method does not handle string arguments causing a TypeError correctly identifies the error. Options B, C, and D are incorrect.
  4. Final Answer:

    The method does not handle string arguments causing a TypeError -> Option D
  5. Quick Check:

    Multiplying Integer by String causes error [OK]
Quick Trick: Check argument types when using arithmetic operations [OK]
Common Mistakes:
MISTAKES
  • Initializing product to 0 (would always return 0)
  • Assuming map replaces each for side effects
  • Using + instead of * for multiplication

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes