Bird
0
0

You want to create a Ruby class Vector2D that supports adding two vectors using +. Which approach best uses the fact that operators are methods in Ruby?

hard📝 Application Q15 of 15
Ruby - Operators and Expressions
You want to create a Ruby class Vector2D that supports adding two vectors using +. Which approach best uses the fact that operators are methods in Ruby?
ADefine <code>def +(other)</code> to return a new Vector2D with summed x and y.
BDefine a separate method <code>add_vectors(v1, v2)</code> outside the class.
CUse a global function to add vector components.
DOverride the <code>+</code> operator to print a message instead of adding.
Step-by-Step Solution
Solution:
  1. Step 1: Use operator method inside the class

    Since operators are methods, defining def +(other) inside Vector2D allows natural use of + to add vectors.
  2. Step 2: Return a new Vector2D with summed components

    The method should return a new Vector2D object with x and y added from both vectors, making code clean and intuitive.
  3. Final Answer:

    Define def +(other) to return a new Vector2D with summed x and y. -> Option A
  4. Quick Check:

    Operator methods enable clean custom behavior [OK]
Quick Trick: Override operator methods inside your class for natural syntax [OK]
Common Mistakes:
  • Defining addition outside the class
  • Using global functions instead of methods
  • Overriding operators for unrelated behavior

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes