- OOP Review + Examples
- Class methods vs. Instance methods?
- What does the keyword
super
do?
We briefly discussed what happens when RSPEC stubs a method and why we need to use the attr_reader in order to check values if a instance variable method reader has been stubbed.
Here are some questions we discussed:
- What is stubbing?
- Why do we use it?
- How does stubbing effect how we write code?
Modules are defined similarly to classes, and can contain methods. However, modules are not bound to a data set the way an instance of a class would be. Modules add functionality and extend classes. Modules should also be treated as re-usable sets of methods that could be added to multiple classes.
Code:
module FUNC
PI = 3.14
def print_the_name
puts "The name is #{@name}"
end
def count_to(num)
(0..num).each do |current|
puts "Current number is #{current}"
end
end
end
class Parent
include FUNC
def initialize(name)
@name = name
end
end
# instantiate a parent
parent = Parent.new("Sarah")
# call module method from instance
parent.count_to(10)
# instantiate a parent
child = Child.new("Johnny")
# namespacing with a module / class
puts "pie is #{Child::PI}"
puts "pie is #{FUNC::PI}"
We also demonstrated that modules can affect inheritance. Once a module is included in a class, it can affect the inheritance chain, particularly if the Module contains an initialize
method.
Code:
module FUNC
PI = 3.14
def print_the_name
puts "The name is #{@name}"
end
def count_to(num)
(0..num).each do |current|
puts "Current number is #{current}"
end
end
end
class Parent
include FUNC
def initialize(name)
@name = name
end
end