views:

157

answers:

2

The following piece of code works perfectly in script/console but returns the following error when i compile the same in a ruby script.:

:in `round': wrong number of arguments (1 for 0) (ArgumentError)

tf={"ph"=>{0=>1.33333333333333, 1=>1.5}, "fee"=>{0=>1.66666666666667}, "test"=>{0=>1.16666666666667, 1=>1.25}, "what"=>{0=>2.0, 1=>2.0}, "for"=>{0=>1.5}, "is"=>{0=>1.83333333333333, 1=>1.75}}

tf.each{|k,v| v.each{|k1,v1| tf[k][k1]=(v1.round(5))}}

Any Ideas ? Cheers !

A: 

From what it looks like, you are not supposed to pass an argument to the round method. You have passed 5 to it.
If you are trying to round it to 5 decimal places, there is no builtin method for that (that I'm aware of). This is a page that explains how to do so: http://solutions.hans-eric.com/rounding-off-floating-point-numbers-in-ruby

bennybdbc
I need to round off each number to 5 decimal places. And interestingly the same piece of code WORKS in the console !
Shreyas Satish
That is interesting. I've edited to include a link that will help you.
bennybdbc
+1  A: 

Float#round seems to work differently in Ruby 1.8 and Ruby 1.9: in 1.8 it complains about the given argument, in 1.9 returns back float properly rounded to the given number of decimals.

But, as the article linked in the other answer wisely says:

you should consider the reason you’re performing the rounding (or equivalent) operation. If it’s for presentation reasons only a better way might be to use a format string instead, and leave the original data intact.

Mladen Jablanović