Access to instance variable outside class

If the instance variable belongs to the class, can I access the instance variable (e.g. @hello ) directly using the class instance?

 class Hello def method1 @hello = "pavan" end end h = Hello.new puts h.method1 
+53
ruby instance-variables
Aug 25 '12 at 14:15
source share
2 answers

Yes, you can use instance_variable_get as follows:

 class Hello def method1 @hello = "pavan" end end h = Hello.new p h.instance_variable_get(:@hello) #nil p h.method1 #"pavan" - initialization of @hello p h.instance_variable_get(:@hello) #"pavan" 

If the variable is undefined (the first call to instance_variable_get in my example), you get nil .




As Andrei mentions in his comment:

You should not do this by default, since you are accessing instance variables, as this violates encapsulation.

It is best to define an accessor:

 class Hello def method1 @hello = "pavan" end attr_reader :hello end h = Hello.new p h.hello #nil p h.method1 #"pavan" - initialization of @hello p h.hello #"pavan" 

If you want a different method name, you can add an alias to the accessory: alias :my_hello :hello .

And if the class is not defined in your code, but in stone: you can change the classes in your code and insert new functions into the classes .

+100
Aug 25 2018-12-12T00:
source share

You can also accomplish this by calling attr_reader or attr_accessor as follows:

 class Hello attr_reader :hello def initialize @hello = "pavan" end end 

or

 class Hello attr_accessor :hello def initialize @hello = "pavan" end end 

Invoking attr_reader will create a getter for this variable:

 h = Hello.new p h.hello #"pavan" 

Calling attr_accessor will create getter AND a setter for this variable:

 h = Hello.new p h.hello #"pavan" h.hello = "John" p h.hello #"John" 

As you understand, use attr_reader and attr_accessor respectively. Use attr_accessor only when you need a getter AND a setter and use attr_reader when you only need a getter

+5
Jul 23 '16 at 17:46
source share



All Articles