Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't modify self in ruby for integer

Tags:

ruby

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!
like image 820
bswinnerton Avatar asked Dec 26 '22 10:12

bswinnerton


1 Answers

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. :)

like image 74
Sergio Tulentsev Avatar answered Jan 08 '23 03:01

Sergio Tulentsev