To add a private property to a class in Ruby, we use the attr_reader
, attr_writer
, or attr_accessor
methods within the class definition. However, to make the property private, we need to define it within the private
block.
Here's an example:
main.rb404 chars17 lines
In this example, we've defined two properties within Example
. @public_property
is defined using attr_reader
, which creates a public getter method for the property. We can access it outside the class using example.public_property
.
@private_property
is also defined using attr_reader
, but it's placed within the private
block. This makes the getter method for @private_property
only accessible within the class. If we try to call example.private_property
from outside the class, we'll get a NoMethodError
.
gistlibby LogSnag