Ruby and self change for Float instance

I would like to change the self value for the 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 round_by! a method that changes the value of an eigenvalue.

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

But I got an error saying that I cannot change the value of self.

Any idea?

+8
ruby
source share
3 answers

You cannot change the value of self . It always points to the current object; you cannot point to anything else.

If you want to change the value of an object, you will either do this by calling other mutation methods, or by setting or changing the values โ€‹โ€‹of the instance variables, rather than trying to reassign self . However, in this case, this will not help you, because Float does not have any mutating methods, and setting instance variables will not buy you anything, because none of the float operations is by default affected by any instance variables.

So bottom line: you cannot write mutating methods in floats, at least not in the way you want.

+10
source share

You can also create a class and save the float in an instance variable:

 class Variable def initialize value = nil @value = value end attr_accessor :value def method_missing *args, &blk @value.send(*args, &blk) end def to_s @value.to_s end def round_by(precision) (@value * 10 ** precision).round.to_f / 10 ** precision end def round_by!(precision) @value = round_by precision end end a = Variable.new 3.141592653 puts a #=> 3.141592653 a.round_by! 4 puts a #=> 3.1416 

Read more about using "class variable" here .

+1
source share

This is a really good question, and I'm sorry to say that you cannot - at least not with the Float class. He is immutable. My suggestion was to create your own class that implements Float (it inherits all methods), e.g. in pseudocode

 class MyFloat < Float static CURRENT_FLOAT def do_something CURRENT_FLOAT = (a new float with modifications) end end 
0
source share

Source: https://habr.com/ru/post/650854/


All Articles