Object Oriented Programming Part 2 Flashcards
How can you define whether methods are public or private and are methods public by default, yes or no?
private
def greeting(name)
puts “Hello, #{name}”
end
Methods are public by default yes
You would think that Ruby needs methods in order to access attributes, how could you edit the following code so that it’s much easier/shorter?
class Person def initialize(name, job) @name = name @job = job end
def name
@name
end
def job=(new_job)
@job = new_job
end
end
class Person
attr_accessor :name
attr_accessor :job
def initialize(name, job) @name = name @job = job end
end
Modules are basically like classes, but what are two main differences between the two?
Modules can’t create instances and can’t have subclasses.
If you want access a module that is not already present in the interpreter, how can you do this? Say you wanted to access the date?
require ‘date’
puts Date.today
When a module is used to mix additional behaviours and information into a class. This is very handy to customize classes without having to rewrite code. What is this called?
It’s called a mixin
Create a basic class with only an initialize method, and make it so that the balance key gets a value of 0 if it takes no argument?
class Account
def initialize(attrs = {}) @balance = attrs[:balance] || 0 end