-3

I created a Test class which has an instance variable @val and which is defined inline.

class Test
 @value = 10
 def display
   puts @value
 end
end

t = Test.new
t.display

This gives no output. But if I set @val through initialize method then the code works.

3
  • 1
    What is o/p? Is it an abbreviation of such a long word to make you feel you cannot type the full word even when you are asking something to someone? Commented Jun 4, 2014 at 12:41
  • possible duplicate of instance variable declaration Commented Jun 4, 2014 at 12:46
  • You could also define it as a class variable indicated by @@ depending on your usage of this variable like class Test; @@value=10; def display; puts @@value; end; end then your proposal will work as expected. Just know that if you change this variable it will change it for all instances of this class since the variable is tied to the class itself and not an instance. Commented Jun 4, 2014 at 14:04

1 Answer 1

3

@val = 10 ( which you wrote in the scope of the class Test) creates an instance variable for your class Test. Where as initialize creates an instance variable for the instances of the class Test.

Look below, for comfirming :-

class Test
  @x = 10
  def initialize
    @x = 12
  end
end

Test.instance_variable_get(:@x) # => 10
Test.new.instance_variable_get(:@x) # => 12
Sign up to request clarification or add additional context in comments.

5 Comments

Thnaks got the answer. So is it a bad practice to define instance variable inline. If not how do I access it.
@Swapnil: No, it's not just "bad practice", it just does not work that way.
Thanks. I am new to ruby and had some problems grasping the facts. If this way I cant access the instance variable via the instance of a that class then does this(inline @x) acts like a global variable(in ruby's space- class variable) and if not then what is the difference between these 2 variable when defined like in your above code.
Classes are objects just like any other object. They can have instance variables just like any other object. You use an instance of an object of class Class exactly the same way and for exactly the same reasons as you would for an object of class Foo or Bar or any other object. There is no difference between those two instance variables except for which object they belong to. They behave exactly the same.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.