add a private property to a class in ruby

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.rb
class Example
  attr_reader :public_property

  def initialize
    @public_property = "I'm publicly accessible!"
    @private_property = "I'm not publicly accessible."
  end

  private

  attr_reader :private_property
end

example = Example.new
puts example.public_property  # Output: "I'm publicly accessible!"
puts example.private_property # Output: NoMethodError - undefined method `private_property'
404 chars
17 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