Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 views
in Technique[技术] by (71.8m points)

ruby - Access instance variable from outside the class

If an instance variable belongs to a 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, you can use instance_variable_get like this:

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 (first call of instance_variable_get in my example) you get nil.


As Andrew mention in his comment:

You should not make this the default way you access instance variables as it violates encapsulation.

A better way is 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 another method name, you could alias the accessor: alias :my_hello :hello.

And if the class is not defined in your code, but in a gem: You can modify classes in your code and insert new functions to classes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...