I'm looking for a way in ruby to chain 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 something not possible in Ruby?
guesses_left = 3
class Integer
def decrement_guess_count!
self -= 1
end
end
guesses_left.decrement_guess_count!
That's by design. It's not specific to integers, all classes behave like that. For some classes (String
, for example) you can change state of an instance (this is called destructive operation), but you can't completely replace the object. For integers you can't change even state, they don't have any.
If we were willing to allow such thing, it would raise a ton of hard questions. Say, what if foo
references bar1
, which we're replacing with bar2
. Should foo
keep pointing to bar1
? Why? Why it should not? What if bar2
has completely different type, how users of bar1
should react to this? And so on.
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 challenge you to find a language where this operation is possible. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With