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
fooreferencesbar1, which we’re replacing withbar2. Shouldfookeep pointing tobar1? Why? Why it should not? What ifbar2has completely different type, how users ofbar1should react to this? And so on.I challenge you to find a language where this operation is possible. 🙂