In Ruby, operators like + are actually methods. What will this code print?
class Number attr_reader :value def initialize(value) @value = value end def +(other) Number.new(@value + other.value + 1) end def to_s @value.to_s end end n1 = Number.new(2) n2 = Number.new(3) puts (n1 + n2).to_s
Remember the + method adds the two values and then adds 1 extra.
The + method adds @value of both objects and then adds 1 extra, so 2 + 3 + 1 = 6.
Why does Ruby treat operators like + and - as methods?
Think about how you can change how + works for your own classes.
Operators as methods let you define how operators behave for your own objects, enabling operator overloading.
What error will this code produce?
class Box def +(other) @size + other.size end end b1 = Box.new b2 = nil puts b1 + b2
Check if @size is initialized before use.
The instance variable @size is never set, so it is nil. Calling + other.size tries to call size on nil, causing a NoMethodError.
* operator method in Ruby?Choose the correct way to define the * operator method that multiplies two objects' values.
Remember the operator method name is the operator symbol itself.
Option C correctly defines the * method with parentheses and parameter. Option C has a space causing syntax error. Option C is invalid syntax. Option C defines a different method name.
Consider this Ruby code. What will it print?
class Animal def +(other) "Animal plus Animal" end end class Dog < Animal def +(other) super + " and Dog plus Dog" end end d1 = Dog.new d2 = Dog.new puts d1 + d2
Look at how super is used inside the + method in Dog.
The Dog class calls super to get the Animal + method result, then adds its own string. So the output combines both strings.