call a setter on an instance of a class in ruby

To call a setter method on an instance of a class in Ruby, you first need to define the setter method in your class. A setter method is an instance method that allows you to set the value of an instance variable.

Here's an example of how to define a setter method for an instance variable @name:

main.rb
class Person
  def name=(name)
    @name = name
  end
end
58 chars
6 lines

In this example, name= is the name of the setter method, and name is the parameter that represents the new value you want to set for the @name instance variable.

To call the setter method on an instance of the class, you simply use dot notation and pass the new value as an argument:

main.rb
person = Person.new
person.name = "John Doe"
45 chars
3 lines

In this example, person.name = "John Doe" calls the name= setter method on the person instance and sets the value of @name to "John Doe".

gistlibby LogSnag