Can't change self in ruby to integer
I'm looking for a way in ruby to bind a destructive method to change the value of a variable by one, but I'm getting errors saying Can't change the value of self
. Is this possible in Ruby?
guesses_left = 3
class Integer
def decrement_guess_count!
self -= 1
end
end
guesses_left.decrement_guess_count!
source to share
This is by design. It is not integer specific, all classes behave like this. For example, for some classes ( String
), you can change the state of the instance (this is called a destructive operation), but you cannot completely replace the object. For integers, you cannot change the even state, they are not.
If we were willing to resolve such a thing, it would raise a lot of difficult questions. Let's say that if it foo
refers to bar1
, which we replace with bar2
. Should I foo
point to bar1
? What for? Why shouldn't it? What if it bar2
is of a completely different type, how bar1
should users react to it? Etc.
class Foo
def try_mutate_into another
self = another
end
end
f1 = Foo.new
f2 = Foo.new
f1.try_mutate_into f2
# ~> -:3: Can't change the value of self
# ~> self = another
# ~> ^
I suggest you find the language in which this operation is possible. :)
source to share