开发者

Instance variable in ruby

class Test
   def initialize
     @var = "125"
   end
   def testmethod
     puts @var
     puts "accessing me from child class"
   end
 end

class TestExtension < Test

  def method1
    puts @var = "One Hundred and twenty five"
    testmethod()
  end
end

t = Test.new
p = TestExtension.new
p.method1
t.testmethod

output:

One Hundred and twenty five
One Hundred and twenty five
accessing me from child class
125
accessing me from child class

My question is that accessing the testmethod() in child class TestExtension results in acces开发者_Go百科sing that value of @var which is being declared in TestExtension class instead of accessing the value which is being declared in Test class . Is it correct ?


Short answer:
Yes

Slightly longer answer:
Instance variables are, as their name suggests, per instance. For every object there can only be one variable called @var, regardless of which class has the code to access it.


It is correct.

As Gareth said, instance variables belong to instances, not classes.

If you want variables to belong to classes, you may use instance variable of class object (err, this term is to complex to write it correctly).

In short, everything in Ruby is an object, including classes. In the following example Base and Derivative are just constants which contain a reference to objects. Those objects represent classes (ta-da!).

Taking this fact into account, we can do the following:

class Base
  @var = 1

  def self.change(new_value)
    @var = new_value
  end

  def self.to_s
    "#{self.name}, @var = #{@var}"
  end  
end

class Derivative < Base; end

Derivative.change(2)

puts Base         # => Base, @var = 1
puts Derivative   # => Derivative, @var = 2
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜