00:00
04:33

RFS: Getter and Setter Methods - 009

Setter and Getter methods are some of the most simple methods we can implement in our classes. Let's take a look.

Getter Method

class Product  def name    @name  endend

In this example we define a method reading the @name instance variable. You might be wondering "what's an instance variable?" simple they are just variables that are bound to the instance. They can be accessed from anywhere inside of the class. Let's define the setter method.

Setter Method

class Product  def name=(str)    @name = str  endend

This method allows us to set the value of the @name instance variable.

Putting it Together

class Product  def name    @name  end    def name=(str)    @name = str  endend

We now have a simple product class that can 'get' the value from the instance variable and 'set' the value of the instance variable.

product = Product.newproduct.name = "God of War"product.name=> "God of War"

That's it for this post! In the next post we'll see how we can simplify our code.