nuke root
nuke root

Reputation: 3

+= operator overloading in ruby

class Fracpri
attr_accessor:whole, :numer, :denom, :dec, :flofrac
def initialize()
    puts "Hey! It's an empty constructor"
end
def getFraction(whole,numer,denom)
    @whole=whole
    @numer=numer
    @denom=denom
end
def showFraction
    puts "#{whole} #{numer}/#{denom}"
end
def +=(obj)
    if(self.whole+(self.numer.to_f/self.denom.to_f) < obj.whole+(obj.numer.to_f/obj.denom.to_f))
        puts "Yes"
    else
        puts "No"
    end
end

end
puts "10 question"
r3=Fracpri.new()
r3.getFraction(1,2,3)
r2=Fracpri.new()
r2.getFraction(4,6,5)
r1=Fracpri.new()
r1.getFraction(2,6,5)
r1 += r2

this is the error message I'm getting:

syntax error, unexpected '=', expecting ';' or '\n'

    def +=(obj)
          ^

 syntax error, unexpected keyword_end, expecting end-of-input

suggest me how to rectify this error so that i can perform overloading,i need to add a constant using "+=" operator

Upvotes: 0

Views: 95

Answers (1)

max pleaner
max pleaner

Reputation: 26768

It is not possible to override =, nor variants such as +=. These are built in keywords and not methods such as +.

If you change your patch from def +=(obj) to def +(obj), you can still call r1 += r2 and it will have the same effect as if you'd patched +=. This is because += is calling your patched + method under the hood.

By the way, your + method doesn't actually return a value so any time you call += it will always result in nil .... but it seems like this is still a WIP so hopefully you can sort that bit out.

Upvotes: 3

Related Questions