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 .
knut Aug 25 2018-12-12T00: 00Z
source share