Phani
Phani

Reputation: 1754

Instance variables in ruby

 class Sample
   attr_accessor :x,:y

   def initialize 
     @x = "x"
     y = "y"     
   end
 end     

 Sample.new.instance_variables  => [:@x] 

class Sample
  attr_accessor :x,:y

  def initialize 
     @x = "x"
     self.y = "y"     
  end
end  

Sample.new.instance_variables => [:@x, :@y] 

Can anyone let me know what is going on here. Why is y an instance_variable second time?

Upvotes: 1

Views: 103

Answers (3)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230521

This line

attr_accessor :y

creates a couple of methods

def y
  @y
end

def y= val
  @y = val
end

So, when you call y= method, @y instance variable jumps to life. In second snippet you correctly call y= method. But in the first one you simply create an unused local variable y (setter method is not called and ivar is not created).

Upvotes: 1

Jim Deville
Jim Deville

Reputation: 10672

attr_accessor :y defines methods that are roughly equivalent to

def y
  @y
end

def y=(val)
  @y = val
end

So, when you assign to self.y, you are assigning to an instance variable due to the attr_accessor macro

Upvotes: 8

halfelf
halfelf

Reputation: 10107

Why not? self is an instance and y is an instance var. In the first example, y is only a normal local var.

Upvotes: 1

Related Questions