Error while overloading the '/' operator

Hi,

I tried to overload the operator ‘/’ with float figures :

class Float

def /(dividande)
if (self.to_f == 0.0 or dividande.to_f == 0.0)
return 0.0
else
return self.div(dividande)
end
end

end

But when I use it I’ve got this error :

./common/tools.rb:7:in /': stack level too deep (SystemStackError) from ./common/tools.rb:7:indiv’

so this line “return self.div(dividande)”

Does anyone can help me ?

Thanks

Lune L. wrote:

Hi,

I tried to overload the operator ‘/’ with float figures :

class Float

def /(dividande)
if (self.to_f == 0.0 or dividande.to_f == 0.0)
return 0.0
else
return self.div(dividande)
end
end

end

But when I use it I’ve got this error :

./common/tools.rb:7:in /': stack level too deep (SystemStackError) from ./common/tools.rb:7:indiv’

so this line “return self.div(dividande)”

Does anyone can help me ?

Thanks

Have you considered the following possibility?
using your code… I try to do this:

5.5 / 7
The program says "Okay, 5.5 isn’t 0 and 7 isn’t 0, so I’m going to …
Go to this “divide” function there, which tells me to check whether 5.5
is 0 and 7 is 0, and otherwise I have to go … to this “divide”
function there, which tells me to check …

What you’re really looking for is a way to call the old “divide” method.
The usual way of doing it is to first alias the original method to
another name (something like
“boo_i_hate_the_original_dividing_for_floats”), and then call that
method in your code if it is warranted.

Robert W. wrote:

Sorry, this is somewhat picky, but this is not method “overloading.”
This is method “overriding” since you are replacing the existing method
with your own. Method overloading is something completely different.
Ruby does not directly support method overloading.

Hum. Ignore this. I misread the OP a little by thinking “method
overloading” as opposed to “operator overloading.” Although, in Ruby
this can often be somewhat of a gray area, given that Ruby operators
basically are methods. It does confuse terminology somewhat.

Lune L. wrote:

I tried to overload the operator ‘/’ with float figures :

class Float

def /(dividande)
if (self.to_f == 0.0 or dividande.to_f == 0.0)
return 0.0
else
return self.div(dividande)
end
end

end

Sorry, this is somewhat picky, but this is not method “overloading.”
This is method “overriding” since you are replacing the existing method
with your own. Method overloading is something completely different.
Ruby does not directly support method overloading.

http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/234117