Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby - attr - should i use @ or getter without @?

Tags:

ruby

I see that with this code:

# filename: play.rb
class A
  attr_reader :a
  def initialize(num)
   @a=num # I have to use @ here
  end

  def m1
    p "---"
    p @a
    p a 
  end 
end

obj = A.new(1)
obj.m1

I get the output

$ ruby play.rb 
"---"
1
1

As you see I can refer to a as either @a or a in the m1 method and both work.

Which should I use when and why?

like image 455
Michael Durrant Avatar asked Nov 22 '19 14:11

Michael Durrant


1 Answers

In this case you don't use a local variable a but a getter method that gives you @a because that's have attr_reader :a. It generates a method #a() used as an getter.

What you really do is:

  def m1
    p "---"
    p @a
    p a() 
  end 

If I have the accessor, I use it, not the instance variable. It lets me change the getter later.

like image 52
mrzasa Avatar answered Sep 22 '22 05:09

mrzasa