Take the example class:
# in ./example.rb
class Example
private
attr_accessor :name
end
When I run it in verbose mode, Ruby throws warnings at me:
$ ruby -W2 ./example.rb
example.rb:3: warning: private attribute?
Why is this not recommended?
Because it doesn't make much sense to define a getter/setter that is not visible from the outside in most cases. We generally use attr_accessor
only to expose an instance variable outside of the class. However, the private
keyword defeats this purpose by making the generated getter/setter methods invisible to the outside world.
The only reason you would want to use a private setter/getter is when there is some additional logic involved. In this case, however, you would have to define those methods manually with def
, anyway.