I am having an application on Ruby On Rails.
In application I want to override parent class of division in Ruby.
For handling below exceptions.
I Googled everywhere. I want to override ruby division method in application.
So that for below results it should return zero.
0.0 / 0
=> NaN
1.0 / 0
=> Infinity
ZeroDivisionError: divided by 0
I can handle it by changing code everywhere while divide operation. But I want to save my time by overriding the method itself.
You do not need a special method or to extend the float class as other answers state.
Ruby provides you a method on the Float class for this called .finite?
http://ruby-doc.org/core-1.9.3/Float.html#method-i-finite-3F
finite? → true or false Returns true if flt is a valid IEEE floating point number (it is not infinite, and nan? is false).
if value.finite? == false
value = 0
else
value = value
end
The above example is a bit verbose.
Very similar to: How can I redefine Fixnum's + (plus) method in Ruby and keep original + functionality?
class Float
alias_method :old_div, :/
def /(y)
return NAN if self == y && y == 0.0
return INFINITY if self == 1.0 && y == 0.0
self.old_div(y)
end
end
I know the code above might not be what you exactly want. Feel free to customize it the way you want =)
Overriding the division of Fixnum, Decimal, etc. is possible, but might not be the best solution for you. You would need to override methods in several classes, and they might have some very nasty side-effects (remember - these methods are not called only from your code!!)
I would suggest you write some helper module, which will implement this new behavior, and that you would call it instead of /:
module WeirdMath
self.div(n1, n2)
result = n1 / n2
result.nan? || result.infinite? ? 0 : result
rescue
0
end
end
WeirdMath.div(0.0, 0) # => 0
WeirdMath.div(1.0, 0) # => 0
WeirdMath.div(3.0, 2) # => 1.5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With