Back to Library
Region:
Switch to ID
Beginner Exercism • ruby
Instance Variables
Lesson Overview
# Introduction
About
Key Points:
- When a class’
.newmethod is called to create an object instance, the.initializemethod is passed all arguments to initialize the instance’s state. - instance variable names are prefixed with
@. - instance variables default to
niluntil they are explicitly set. - instance variables are private by default, and they should be manipulated with getters and setters
class Backpack
initialize(owner)
@owner = owner
end
def owner
@owner
end
def owner=(new_owner)
@owner = new_owner
end
end
- Methods named with a trailing
=are recognized as setters by Ruby, and allow the syntactic “sugar” use of the assignment syntax, e.g.Backpack.new("Sven").owner = "Ayah". Notice the space betweenownerand=while the actual method name isowner=. - Getters and setters can be created using the
attr_reader,attr_writer, andattr_accessormethods:attr_reader: Create getters for the symbols listedattr_writer: Create setters for the symbols listedattr_accessor: Create getters and setters for the symbols listed
class Backpack
attr_accessor :owner
initialize(owner)
@owner = owner
end
end
- Why use getters and setters rather than the instance variable directly?
- If there was a typographical error (we call these “typo”) in the previous example (e.g.
@ownar), it would fail silently, potentially introducing a bug into the system. - Getters and setters make this explicit, and will raise an error when a typo is made
- If there was a typographical error (we call these “typo”) in the previous example (e.g.
References
Initializing object instances
Instance variables
- Ruby For Beginners: Instance variables
- Ruby Guides: Instance variables
- Ruby User’s Guide: Instance variables
- Geeks for Geeks: Ruby Getters and Setters Methods
- Mix & Go: Ruby’s attr_accessor, attr_reader, attr_writer
Originally from Exercism ruby concepts