-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.

undur_gongor
  • 15,657
  • 5
  • 63
  • 75
Swapnil
  • 21
  • 4
  • 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? – sawa Jun 04 '14 at 12:41
  • possible duplicate of [instance variable declaration](http://stackoverflow.com/questions/14033009/instance-variable-declaration) – toro2k Jun 04 '14 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. – engineersmnky Jun 04 '14 at 14:04

1 Answers1

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
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
  • Thnaks got the answer. So is it a bad practice to define instance variable inline. If not how do I access it. – Swapnil Jun 04 '14 at 12:45
  • @Swapnil: No, it's not just "bad practice", it just does not work that way. – undur_gongor Jun 04 '14 at 12:47
  • 1
    @Swapnil Read: http://stackoverflow.com/a/3803089/1376448 – kiddorails Jun 04 '14 at 12:47
  • 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. – Swapnil Jun 04 '14 at 12:53
  • 1
    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. – Jörg W Mittag Jun 04 '14 at 16:01