Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby and modifying self for a Float instance

Tags:

ruby

I would like to change the self value of a float instance.

I have the following method :

class Float
  def round_by(precision)
    (self * 10 ** precision).round.to_f / 10 ** precision
  end
end

And I would like to add the round_by! method which will modify the self value.

class Float
  def round_by!(precision)
    self = self.round_by(precision)
  end
end

But I got an error saying I can't change the value of self.

Any idea ?

like image 721
Arkan Avatar asked Jan 09 '11 17:01

Arkan


People also ask

Can instance variables be changed?

An instance variable is a variable that is specific to a certain object. It is declared within the curly braces of the class but outside of any method. The value of an instance variable can be changed by any method in the class, but it is not accessible from outside the class.

How do you declare an instance variable in Ruby?

The ruby instance variables do not need a declaration. This implies a flexible object structure. Every instance variable is dynamically appended to an object when it is first referenced. An instance variable belongs to the object itself (each object has its own instance variable of that particular class)

Can Ruby modules have instance variables?

It is well known that Ruby has instance and class variables, just like any Object-Oriented language. They are both widely used, and you can recognize them by the @a and @@a notation respectively.

Are Ruby instance variables private?

Unlike methods having different levels of visibility, Ruby instance variables are always private (from outside of objects). However, inside objects instance variables are always accessible, either from parent, child class, or included modules.


1 Answers

You can't change the value of self. It always points to the current object, you can't make it point to something else.

When you want to mutate the value of an object, you either do this by calling other mutating methods or setting or changing the values of instance variables, not by trying to reassign self. However in this case, that won't help you, because Float doesn't have any mutating methods, and setting instance variables won't buy you anything, because none of the default float operations are affected by any instance variables.

So the bottom line is: you can't write mutating methods on floats, at least not in the way you want.

like image 78
sepp2k Avatar answered Oct 11 '22 06:10

sepp2k