Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby division infinity/NaN should return 0

Tags:

ruby

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.

like image 515
Sumit Munot Avatar asked Feb 17 '14 20:02

Sumit Munot


3 Answers

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.

like image 114
jBeas Avatar answered Nov 12 '22 01:11

jBeas


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 =)

like image 4
Abdo Avatar answered Nov 12 '22 00:11

Abdo


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
like image 2
Uri Agassi Avatar answered Nov 12 '22 00:11

Uri Agassi