Search code examples
rubysetterstring-interpolationattr-accessor

String interpolation update after change


I have values in an interpolated string that refer to an array like this:

attr_accessor :s, :gamespace

def initialize
  @s = [1,2,3]
  @gamespace = "#{@s[0]} | #{@s[1]} | #{@s[2]} "
end

When I change the value of @s, it doesn't update the value of @gamespace.

I resorted to making an additional method like this:

def gamespace
  @gamespace = "#{@s[0]} | #{@s[1]} | #{@s[2]}"
end

and then I call it after any change to @s.

Is there a way to let attr_accessor update the string interpolation after a change without writing this method?


Solution

  • A reader method only refers to an instance variable, it doesn't re-evaluate it. If you want to use a reader method to get an updated value, the only thing you can do is to not use the default setter method, but write your own.

    def s= a
      @s = a
      @gamespace = "#{a[0]} | #{a[1]} | #{a[2]} "
    end
    

    Setting @a should not be done directly, but should always be done through s=. This applies to initialize as well:

    def initialize; s=([1, 2, 3]) end