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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With