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.rb253 chars14 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