Creating Your Own Version of attr_accessor : class_eval « Reflection « Ruby






Creating Your Own Version of attr_accessor

class Class
  def add_accessor(accessor_name)
    self.class_eval %Q{
      def #{accessor_name}
        @#{accessor_name}
      end

      def #{accessor_name}=(value)
        @#{accessor_name} = value
      end
    }
  end
end

 

 








Related examples in the same category

1.class_eval is ideal for adding methods to a class dynamically: