add a property to a class in ruby

In Ruby, you can add a property (also known as an attribute) to a class by defining an instance variable and creating accessor methods to read and write its value.

Here's an example:

main.rb
class Person
  attr_accessor :name # creates getter and setter methods for @name
  
  def initialize(name)
    @name = name
  end
end

person = Person.new("Alice")
puts person.name # outputs "Alice"

person.name = "Bob"
puts person.name # outputs "Bob"
253 chars
14 lines

In this example, we created a Person class with an attr_accessor for the name instance variable. This generates both a getter and a setter method that can be used to read and update the value of the variable.

We then define an initialize method that sets the initial value of the @name variable when a new Person object is created.

Finally, we create a new Person object with the name "Alice", output its name to the console, and then update its name to "Bob" before outputting it again.

gistlibby LogSnag