Search code examples
rubyvariablesinstanceinstance-variablesclass-instance-variables

How deny creating instance variables in Ruby


I would like to deny creating instance variables in Ruby,to prevent unattended variables being created 'by mistake'.

My class:

class Test
  def initialize
    @a = 'Var A'
  end

  def make_new
    @b = 'Var B' <-- I would like to deny creation of any variables that were not defined during the init
  end
end

Solution

  • You can freeze object instances at the end of initialize method:

    class Test
      def initialize
        @a = 'Var A'
        freeze
      end
    
      def make_new
        @b = 'Var B' # I would like to deny creation of any variables that were not defined during the init
      end
    end
    
    t=Test.new
    p t.instance_variable_get :@a
    # "Var A"
    t.make_new
    #a.rb:24:in `make_new': can't modify frozen Test (RuntimeError)
    #        from a.rb:30:in `<main>'
    t.instance_variable_set :@c, 'Var C'
    # a.rb:31:in `instance_variable_set': can't modify frozen Test (RuntimeError)
    #        from a.rb:31:in `<main>'
    class << t
      @d = 'Var D'
    end
    #a.rb:33:in `singletonclass': can't modify frozen Class (RuntimeError)
    #        from a.rb:32:in `<main>'
    p t.instance_variable_get :@d