OOP Flashcards
attr_accessor
attr_reader
attr_writer
attr_accessor :name, height, :weight
self. name
self. height
self. weight
call the constant variables and instance method by creating an instance object.
# define a class class Box BOX_COMPANY = "TATA Inc" BOXWEIGHT = 10 # constructor method def initialize(w,h) @width, @height = w, h end # instance method def getArea @width * @height end end
# define a class class Box BOX_COMPANY = "TATA Inc" BOXWEIGHT = 10 # constructor method def initialize(w,h) @width, @height = w, h end # instance method def getArea @width * @height end end
my_box = Box.new(10, 20)
puts my_box.getArea => 200
puts Box::BOX_COMPANY => ‘TATA Inc’
puts “Box weight is: #{Box::BOXWEIGHT}”
Write accessor getter and accessor setter methods for the class below.
# define a class class Box # constructor method def initialize(w) @width = w end end
you get 2 methods and 1 ivar(instance variable) using that code.
class Box # constructor method def initialize(w) @width = w end
# accessor methods
def Width
@width
end
# setter methods def width=(value) @width = value end end
Inheritance, pass an argument from child to parent when initialize or with a method.
Inheritance, pass an argument from child to parent when initialize or with a method.
def a_method(one, two, three)
super(one, three)
end
class Person
protected
attr_reader :age
private
attr_reader :name
end
Person
When a method is private, only the class - not instances of the class - can access it. However, when a method is protected, only instances of the class or a subclass can call the method. This means we can easily share sensitive data between instances of the same class type.