add a getter to a class in ruby

To add a getter to a class in Ruby, we can use the attr_reader method. This method creates a getter method for the specified attribute(s).

Here's an example:

main.rb
class Person
  attr_reader :name

  def initialize(name)
    @name = name
  end
end

person = Person.new('John Doe')
puts person.name # Output: John Doe
153 chars
11 lines

In the example above, the attr_reader method creates a name getter method for the Person class. This method returns the value of the @name instance variable.

We can then create a new Person object, and use the name getter method to access its name attribute.

related categories

gistlibby LogSnag