2
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 accessing 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 ?

1
  • 1
    Formatted your code (by putting 4 spaces before all code lines and backticks around all identifiers in your english text). Read this for more info: stackoverflow.com/editing-help Commented Dec 13, 2010 at 7:55

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.