1

Is it possible to mark an instance variable such as @var as unassingnable, such that the following test would pass? The aim is simulate a readonly variable:

class Test
  def initialize(var)
    @var = var
    @var.freeze
    make_unassignable(:@var)
  end

  def set_var(new_var)
    @var = new_var
  end

  def make_unassignable(symbol)
    #insert algorithm here
  end
end

test = Test.new('some var')

expect { test.set_var = 'some other var' }.to raise_error
expect { test.instance_variable_set(:@var, 'some other var') }.to raise_error
4
  • @Andrey: Please remove the duplicate flag. The question you have given is similar but I am asking about disabling the ability to assign a variable altogether (not just build protections via exceptions). Commented Feb 13, 2017 at 11:16
  • Thank you for explaining that. Commented Feb 13, 2017 at 11:24
  • please unaccept my answer since it does not answer the question about making variable unassignable (which is not possible, as another answer correctly states) Commented Feb 13, 2017 at 12:42
  • There are read-only variables in Ruby (for example $<), but Ruby doesn't expose this feature through its API. Commented Feb 13, 2017 at 13:03

1 Answer 1

3

No, this is not possible. Variables are variable in Ruby, always. In fact, even constants are variable in Ruby, they only generate a warning when re-assigned.

Sign up to request clarification or add additional context in comments.

1 Comment

Overwritten instance_variable_set on Test’s eigenclass might drastically hamper it’s resetting (not to make it impossible, though.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.