I have a small repository of utility code that almost all of my Ruby projects require because I find them so beneficial to what I do. One such function is a quick precision hack for the Float class. Here’s the code:
class Float def prec(x) sprintf("%.0" + x.to_i.to_s + "f", self).to_f end end
This is nice, because it allows you to quickly round a float to a certain decimal value without having to resort to much trickery.
irb> i = 100.0 / 9.4 => 10.6382978723404 irb> i.prec(2) => 10.64
It did get me thinking though: is there a smarter way of implementing this method?
We can get rid of the sprintf and just use the % method.
class Float def prec(x) (("%.0" + x.to_i.to_s + "f") % self).to_f end end
It still seems to me like that code could be simplified even further. Do any of you have any ideas how to make it any more compact?