Object Oriented Programming in Ruby Flashcards
Define a Class: Dog,
let it have a Function: bark.
It can say anything you want.
class Dog
def bark
“woof”
end
end
Given a class named Dog, create a child class that inherrits the bark method.
bonus, can you override the bark method?
Class ChildDog < Dog
end
Class ChildDog < Dog
def bark
“miauw”
end
end
Make a class named MathFunctions. Then outside the class, define a classmethod for Mathfunctions called Tripple. It should take variable and tripple's it.
Class MathFunctions
en
def MathFunctions.tripple(var)
var *3
end
Write an initializer for Person(name),
Write the getter and setter Method,
don’t use any of the attr_<***>.
Class Person
def initialize(name)
@name = name
end
def name
@name
end
def name=(new_name)
@name = new_name
end
How would you build a contructor for a Person Class
He/She needs a name and age!
def initialize(name, age)
@name = name
@age = age
end
Make a onliner for attribute setter
and getter for the variable: name
attr_accessor :name
For the initialize constructor:
Let age be a Class Method.
given initialize only takes name and age.
check if age is not over 120.
def initialize(name, ageVar)
@name = name
self.age = ageVar
end
def age=(new_age)
@age = new_age unlesss new_age > 120
end
There basicly 3 ways to add a Class Method,
witch ones?
Where should they be declared?
inside the class:
class << self
def method_in_class_in_class
end
end
def self.method_in_class
end
outside the class:
def TheClass.theMethod(variables)
end
Define a class variable named: counter
@@counter
How would a method look like
inside the scope of a constructor?
example:
def initialize(age)
self.age = age
end
def age=(new_age)
@age ||= 5
@age = new_age unless new_age > 120
end
Scope: Constants
How is a Constant defined,
whats the diffrent with normal variables?
MyConstant = “This string is a constant”
- Inner scope can see Constants defined on the outside, and even change them.
- The value of the outher scope doesn’t change with changing the Constant on the inner scope.
# define v1 = "outside" outside of a class define v1="inside" inside of a class MyClass,
inside of a class my_method.
v1 = “outside”
class MyClass
def my_method
v1 = “inside”
end
end
Define a module named: Test,
in with a constant pi lives.
it should hold the value of pi (3.14 )
The module should have a inner class,
and a method putting out pi.
How would you call it ?
How would you include it?
module Test
PI = 3.14
class Test2
def what_is_pi
puts PI
end
end
end
Test::Test2.new.what_is_pie # => 3.14
Would a constant defined inside module,
be readeble for a class outside that module? or a class inside in that module?
it would if the module would be included, like
require_relative ‘module’ .
Yes, classes can handle Constants in Modules defined on the outher scope.
Implement a module namend “foobar”.
include ‘foobar’