Classes and Objects Flashcards
What do ‘states’ do?
States track attributes for individual objects.
What does ‘behavior’ do?
Behaviors are what objects are capable of doing.
How are instance variables scoped?
Instance variables are scoped at the object (or instance) level, and are how objects keep track of their states.
Describe an instance method.
Instance methods define the behaviors in a class. Instance methods defined in a class are available to objects (or instances) of that class.
What is the initialize method often called.
We refer to the initialize method as a constructor, because it gets triggered whenever we create a new object.
What is an instance variable?
An instance variable is a variable that exists as long as the object instance exists, and it is one of the ways we tie data to objects. It does not “die” after the initialize method is run. It “lives on”, to be referenced, until the object instance is destroyed. Every object’s state is unique, and instance variables are how we keep track.
What do instance methods do within a class?
Instance methods allow all objects of the same class to have the same behaviors, though they contain different states.
What is attr_reader?
This is a getter method that takes a symbol as an argument. An example of how it replaces the code for a getter method is:
Getter method:
def name
@name
end
replaced by : attr_reader :name
What is attr_writer?
This is a setter method that takes a symbol as an argument. An example of how it replaces the setter method is:
Setter method
def set_name=(name)
@name = name
end
replaced by : attr_writer :name
What is attr_accessor?
This is a Setter and a Getter method which takes a symbol as an argument.
attr_accessor :name
Why not just reference the syntax for instance variables (@instance_variable) when using a setter or getter method?
Technically, you could just reference the instance variable, but it’s generally a good idea to call the getter method instead.
ie) “#{name} is old.” = getter method
“#{@name} is old.” = instance variable
How many methods does this line of code give us?
attr_accessor :name, :height, :weight
6 - (name, name=, height, height=, weight, weight=)
How do you disambiguate setter methods and creating a local variable?
Prefixing ‘self’ to the setter method name (i.e.. self.name). This tells Ruby that we’re calling a setter method, not creating a local variable. To be consistent, we could also adopt this syntax for the getter methods as well, though it is not required.
What are class methods?
Class methods are methods we can call directly on the class itself, without having to instantiate any objects.
Why do we need a class methods?
Class methods are where we put functionality that does not pertain to individual objects.
def self.what_am_i # Class method definition "I'm a GoodDog class!" end
GoodDog.what_am_i # => I’m a GoodDog class!