[RCR] Floating point division operator /. (or fdiv method)

From: David A. Black [mailto:dblack@wobblini.net]
Sent: Wednesday, June 02, 2004 5:26 PM

Every now and then I accidentially pass an integer to a
method and am
surprised than I get a wrong result. The reason is that the method
expected floats as arguments and not integers. These kind
of bugs are
very hard to find, IMHO.

Agreed, but is it really necessary.

Imagine the following method:

def meth(a, b)
a / b
end

It works if a, b or both are floats, but not if both are integers.

Instead you have to write:

a.to_f / b

or

a / b.to_f

or

1.0 * a / b

Shouldn’t one use:

def meth( a, b )
a.to_f / b.to_f
end

meth(1,3) => 0.333333333333333
meth(“str”,3) => 0.0
meth(“2”,3) => 0.666666666666667

Since the parameters are typeless, one shouldn’t assume that such an
expression will work. This explicitly states the desire of the method and
dictates the function result. It provides maximum flexibility without using
‘special-case’ functions.

Or alternatively:

class Float
alias fdiv /
end

class Integer
def fdiv(divisor)
self.to_f / divisor
end
end

a.fdiv(b)

Any comments?

I like fdiv better than adding a ./ operator.

To me, ‘fdiv’ seems like clutter to overcome insufficent programming.

···

-----Original Message-----
On Thu, 3 Jun 2004, Michael Neumann wrote: