Overriding Float.round

R

rpardee

Hey All,

Looking at the google groups archive for this group, it seems that
there's no built-in way to round a float to a particular number of
decimal points. I thought I'd use that as an occasion to try my hand
at extending a built-in class, and wrote this:

class Float
def round(places)
num = ("1" + "0"*places.to_i).to_f
(self*num).round/num
end
end

But when I say:

p = 22.0/7
puts p.round(3).to_s

Ruby comes back with:

C:/Documents and Settings/pardre1/Desktop/DelMe.rb:4:in `round': wrong
number of arguments (0 for 1) (ArgumentError)
from C:/Documents and Settings/pardre1/Desktop/DelMe.rb:4:in `round'
from C:/Documents and Settings/pardre1/Desktop/DelMe.rb:9

What am I doing wrong?

Thanks!

-Roy
 
R

rpardee

Interestingly--it looks like if I call my method "round2", it works.
But I don't understand why I can't override "round".

(And that original .round method is such a disappoointment to me, I
want to completely obliterate it in my program. ;-)
 
R

rpardee

LOL--found my problem. Sorry for polluting the list.

I was misreading the error message to indicate that round was
complaining about getting too *many* arguments--but it was complaining
about getting too *few*--and on the call to Float.round() in my new
version of Float.round(). So this works:

class Float
alias orig_round round
def round(places)
num = ("1" + "0"*places.to_i).to_f
(self*num).orig_round/num
end
end
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,206
Messages
2,571,069
Members
47,675
Latest member
RollandKna

Latest Threads

Top