To add a setter to a class in Ruby, you can use the attr_writer
method, which creates a public setter method for an instance variable of a class.
Here's an example:
main.rb79 chars7 lines
In this example, we defined a Person
class with an instance variable @name
. The attr_writer
method creates a public setter method name=
for this instance variable.
Now, we can create a new instance of the Person
class and use the setter method name=
to set the @name
value of the instance to "John".
gistlibby LogSnag