Override String.to_f method

Hi, I’m trying to override the .to_f method in String class in order to
trunk strings with more than 10 decimals:

class String
def to_f
if self.size > 10
aux = self[0…9]
return aux.to_f

I got this error when it calls super method:

"10.>> “10.2”.to_f
NoMethodError: super: no superclass method `to_f’ for “10.2”:String

How could I override to_f function??

Thank you very much

I think the problem here is you still need the original String#to_f
method, which you have not duplicated. You’re better off creating a new
method for this; perhaps “to_f_truncate” which then calls the unmodified
to_f and modifies the results.

It’s also a very bad idea to modify such an essential core class like
that. Better to make your own subclass and use that, or make a method
within a specific scope so you don’t destroy the behaviour of everything
sharing the same runtime environment. You’d probably be surprised how
often to_f is used in the underlying components of your program.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs