Bird
0
0

You want to create a class Money where the + operator adds amounts but only if currencies match. How would you implement the + method?

hard📝 Application Q8 of 15
Ruby - Operators and Expressions
You want to create a class Money where the + operator adds amounts but only if currencies match. How would you implement the + method?
AAdd amounts ignoring currency differences.
BUse global variable to store currency and add amounts.
COverride + to always return zero.
DCheck currency equality, then add amounts; else raise error.
Step-by-Step Solution
Solution:
  1. Step 1: Understand requirement

    Only add amounts if currencies are the same to avoid mixing money types.
  2. Step 2: Implement + method logic

    Check if currencies match; if yes, add amounts; else raise an error.
  3. Final Answer:

    Check currency equality, then add amounts; else raise error. -> Option D
  4. Quick Check:

    Safe operator method checks conditions = B [OK]
Quick Trick: Validate operands inside operator methods for safety [OK]
Common Mistakes:
  • Ignoring currency differences
  • Using global variables for currency
  • Returning wrong values intentionally

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes