ruby - How to access instance variable of a module from abother module? -


i have module

module somemodule   @param = 'hello' end  module reporter   include somemodule   def self.put     puts @param   end end 

when call reporter::put no output, suppose reporter module has no access instance variable @param. there way access variable reporter module?

instance variables called instance variables, because belong objects (aka "instances"). there 2 objects in example: somemodule , reporter. both have own instance variables. somemodule has instance variable named @param , reporter has instance variable named @param. 2 instance variables unrelated, though have same name. imagine chaos, if every object had come own names instance variables!

is there way access variable reporter module?

no. cannot access instance variables different objects. object has access own instance variables.

[note: is possible using reflection (e.g. object#instance_variable_get, basicobject#instance_eval, or basicobject#instance_exec), of course. lots of things possible using reflection.]

what can do, however, create method gives access read instance variable. such method called attribute reader:

module somemodule   def self.param; @param end   @param = 'hello' end  module reporter   def self.put     puts somemodule.param   end end 

there method automatically generates such methods you, called module#attr_reader:

module somemodule   class << self; attr_reader :param end   @param = 'hello' end  module reporter   def self.put     puts somemodule.param   end end 

if want write instance variable, need define corresponding attribute writer method:

module somemodule   class << self     attr_reader :param      private      def param=(param)       @param = param     end   end    self.param = 'hello' end  module reporter   def self.put     puts somemodule.param   end end 

there corresponding method named module#attr_writer generates attribute writer method you:

module somemodule   class << self     attr_reader :param      private      attr_writer :param   end    self.param = 'hello' end  module reporter   def self.put     puts somemodule.param   end end 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -