Locked lesson.
About this lesson
How to create a class setter and why you should.
Exercise files
Download this lesson’s related exercise files.
Class Setters.docx59 KB Class Setters - Solution.docx
59.6 KB
Quick reference
Class Setters
To set things in a class, use a setter.
When to use
Use a setter whenever you create a getter in a class.
Instructions
To create a setter in a class:
class Square
def initialize(side_length)
@side_length = side_length
end
# Create Getter
def side_length
return @side_length
end
# Create Setter
def side_length=(side_length)
@side_lenght = side_length
end
end
Hints & tips
- Setters let you set things in a class.
- To name your setter method, use your same instance variable name, but put an equal sign on it.
Lesson notes are only available for subscribers.