0

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
3
  • 2
    1. Those are not "class instance variables", just regular instance variables. Terminology is important. 2. because of attr_accessor :name Commented Feb 7, 2017 at 15:51
  • with attr_reader :name I have the same, so is there any way I can avoid this behavior but still be able to read the instance variable? Commented Feb 7, 2017 at 16:17
  • yeah, why do you put attr_accessor / attr_reader there, again? Commented Feb 7, 2017 at 16:24

1 Answer 1

3

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.

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

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.