Alina
Alina

Reputation: 2261

Ruby access instance variables from another method

I have a class and I try to access an instance variable and I noticed I can do it in both ways by addressing it with @ and without it. Why si there no error when I call it without a @ puts "name : #{name}"?

class Blabla
    attr_accessor :name

    def initialize(blabla)
        @name = blabla
    end

    def populate()
        puts "name : #{name}"
        puts "name : #{@name}"
    end

end

Upvotes: 0

Views: 2149

Answers (1)

Sagar Pandya
Sagar Pandya

Reputation: 9508

As hinted in the comments:

attr_accessor :name

is shorthand for:

def name
  @name
end

def name=(name)
  @name = name
end

So expanding your code we have:

class Blabla    
  def name
    @name
  end

  def name=(name)
    @name = name
  end

  def initialize(blabla)
    @name = blabla
  end

  def populate()
    puts "name : #{name}"
    puts "name : #{@name}"
  end
end

#{name} references the method name which returns @name.

#{@name} references @name directly.

Also be sure to understand attr_reader, attr_writer methods.

Upvotes: 3

Related Questions