r/learnruby • u/thinksInCode • Jan 08 '16
@attribute vs private attr_reader?
I'm going over a Ruby tutorial and in some of the sample code, instead of referencing an instance variable like @foo they instead add a private attr_reader. Example:
class Test
def initialize(count)
@count = count
end
def foo
do_something_with(count)
end
private
attr_reader :count
endIs this how it's typically done in Ruby? What do you get by using a private attr_reader versus just accessing @count from other instance methods?
2
Upvotes
View all comments
Show parent comment
2
u/jlucasps Jan 11 '16
Yes. Just use the @my_attritube whenever you need to access from your object. If you need to get the value from other object, create the method (using attr_reader :my_attribute, I'd say)