ruby - Making a class instance variable unwritable from outside world -


class event      @event_list = {}      attr_reader :name, :value      def initialize(name, value)       @name  = name       @value = value     end      def to_s       "#{@value}"     end      class << self        def event_list           @event_list       end        def event_list=(value); end        def register_event(name, value)           @event_list[name] = event.new(name, value)       end        def registered_events           event_list       end     end end 

in above code snippet can access @event_list using event.event_list, interesting thing able modify variable outside

event.event_list[:name] = "hello" event.event_list  # => { :name => 'hello' } 

how can avoid ?, don't want modify @event_list outside.

as far know, can't stop outside code modifying instance variables in ruby. if don't use attr_reader , attr_writer can still accessed using object#instance_variable_set. ruby doesn't have private variables (or constants), variables politely asked not modify.

if don't define event_list=, seen indication @event_list private variable. solution problem.

then there problem mutable objects. since objects in ruby sadly mutable, if can reference object can change it.

this can solved object#freeze stops object being modified. unfortunately means not can modify it.

ruby not locking things down. openness core part of language need learn work with.


Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -