M
Michael Neumann
Hi,
I know that introducing new syntax into Ruby is probably far from being
accepted by matz....
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.
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
...
My proposal is to add a /. operator, that treats both arguments as
floats, so that
1 /. 2 # => 0.5
Or alternatively:
class Float
alias fdiv /
end
class Integer
def fdiv(divisor)
self.to_f / divisor
end
end
a.fdiv(b)
Any comments?
IMHO, even better would be if / would always mean floating point
division and an extra // operator would mean integer division, but it's
to late to change now (even for Ruby 2.0)
Regards,
Michael
I know that introducing new syntax into Ruby is probably far from being
accepted by matz....
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.
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
...
My proposal is to add a /. operator, that treats both arguments as
floats, so that
1 /. 2 # => 0.5
Or alternatively:
class Float
alias fdiv /
end
class Integer
def fdiv(divisor)
self.to_f / divisor
end
end
a.fdiv(b)
Any comments?
IMHO, even better would be if / would always mean floating point
division and an extra // operator would mean integer division, but it's
to late to change now (even for Ruby 2.0)
Regards,
Michael