5 OOP in Ruby Flashcards

1
Q

What is OOP?

A

Object-oriented programming (OOP) is a programming paradigm that involves the concept of “objects”
with data fields (attributes that describe the object) and associated procedures known as methods.
Objects, which are usually instances of classes, interact with one another to design applications and
computer programs.
Ruby is a pure object-oriented language, and everything appears to Ruby as an object. String, Number,
TRUE and even a class is an instance of the class Class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a class?

A

Classes are the basic building blocks in Object-Oriented Programming (OOP) & they help you define a blueprint for creating objects.

Objects are the products of the class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is an instance of a class?

A

class Book
end
book = Book.new
book.class # => Book
book.is_a? Book # => true if an object is an instance of a class or parent classes
book.kind_of? Book # => true if an object is an instance of a class or parent classes
book.instance_of? Book # => true if object is an instance of an exact class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you declare and use a constructor in Ruby?

A

The initialize method is a standard Ruby class method and works almost same way as a constructorworks in other
object-oriented programming languages. The initialize method is useful when you want to initialize class variables at
the time of object creation.
class Book
def initialize(title, author, price)
# some code to initialize object
end
end
Book.new(‘The Great Gatsby’, ‘F. Scott Fitzgerald’, 8.99)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you create getter and setter methods in Ruby?

A

To make variables available from outside the class, they must be defined within accessor methods, which are also
known as setter methods.
Similar to accessor methods, you can make setter methods write data to instance variables if necessary.

class Book
def initialize(title, author, price)
@title = title
@author = author
@price = Float(price)
end
def title
@title
end
def title=(value)
@title = value
end
end
book = Book.new(‘The Great Gatsby’, ‘F. Scott Fitzgerald’, 8.99)
book.title # => ‘The Great Gatsby’
book.title = ‘The Great Great Gatsby’ # => ‘The Great Great Gatsby’
To make defining accessors and setters simpler, Ruby provides the attr_reader, attr_writer, and attr_accessormethods.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What if we need both of them for the same variable? What does self mean? When do we use it?

A

The keyword self in Ruby gives you access to the current object—the object receiving the current message.
At the time the method definition is executed, the most you can say is that self inside this method will be some
future object with access to this method.
class S
def self_meth
self
end
end
s = S.new
s.self_meth == s # true

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is a class method? How do you define it?

A

The class method is a method that belongs to the class; in some other languages, it is called the static method.
There are several notations for defining them in Ruby:
class Book
defself.total_amount(*books)
books.map(&:price).sum
end
defself.another
# code
end
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the difference between class variables and class instance variables?

A

Class variables are variables shared between all instances of a class. Class variables are prefixed with two @
characters (@@). A class variable must be initialized within the class definition as shown below.
class Book
attr_reader :title, :author, :price
@@count = 0
definitialize(title, author, price)
@title, @author, @price = title, author, Float(price)
@@count += 1
end
defself.statistics
“Count of books: “ + @@count.to_s
end
end
class CustomBook < Book
end
5.times{ Book.new(‘The Great Gatsby’, ‘F. Scott Fitzgerald’, 8.99) }
Book.statistics # => Count of books: 5
CustomBook.statistics # => Count of books: 5
book = Book.new(‘The Great Gatsby’, ‘F. Scott Fitzgerald’, 8.99)
book.count # => NoMethodError: undefined method ‘count’
Basically, class instance variableslook like
instance variables, but you’ll find them on a
class level.
They work like regular class variables, but they
are different because they are not shared with
subclasses. They belong exclusively to the class
itself.
class Book
attr_reader :title, :author, :price
@count = 0
definitialize(title, author, price)
@title, @author, @price = title, author, Float(price)
# @count += 1 NoMethodError: undefined method ‘+’ for nil:NilClass
# Error above raised since ‘initialize’ is sort of instance method
# and instance variables in instance methods belong to object, not class
end
defself.add
@count += 1
end
defself.statistics
‘Count of add method call: ‘ + @count.to_s
end
end
class CustomBook < Book
@count = 0
end
5.times{ Book.add }
Book.statistics # => Count of add method call: 5
CustomBook.statistics # => Count of books: 0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What are the three levels of method access control for classes, and what do they signify?

A

Ruby offers three levels of protection at the instance method
level: public, private, or protected. Ruby does not apply access
control over instance and class variables.
* Public Methods—Anyone can call public methods. Methods
are public by default except for initialize, which is always
private.
* Private Methods—Private methods cannot be accessed or
even viewed from outside the class. Only the class methods
can access privatemembers.
* Protected Methods—A protected method can be invoked only
by objects of the defining class and its subclasses. Access is
kept within the family.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is super? When and how do we use it?

A

Though you can add new functionality to a derived class, sometimes you would like to change the behavior of an
already-defined method in a parent class. You can do so simply by keeping the method name the same and
overriding the method’s functionality. To call the parent method from the overriding method, use super. By default,
all arguments will be sent to the parent method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are Singleton methods? How do you define them?

A

Ruby’s singleton methods are the methods that can be defined for a specific object only i.e. it works for a single object. These kinds of methods belong to the singleton class or eigenclass and are available exclusively for a single object, unlike the other methods which are available for all the instances of the class.

This feature is more useful where there is a need for the object to possess some unique behavior or methods which the other objects of the class do not own.
Syntax:

def Obj.GFG
# Method body
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is a module? What the difference between a module and a class? Describe some best practices for
using modules.

A

Module
(can be considered as a namespace, which may contain constants, methods, and classes)
Modules are collections of methods and constants. They cannot generate instances. Classes may generate instances (objects), and have per-instance state (instance variables).
* A module should have multipurpose logic.
* A module should not contain any instance variables—instance variables have to do with classes
and objects.
* Do not create a module only to take some methods out of the class—this violates the first point
about multipurpose logic.
* If all your module’s methods begin with self, consider defining those methods without self and
using extend ModuleName in your classes instead of include—this is the difference between
include and extend. extend makes method as class methods for classes, where this module
extends.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the difference between include and extend?

A

In simple words, the difference between include and extend is that ‘include’ is for adding methods only to an instance of a class and ‘extend’ is for adding methods to the class but not to its instance.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How does Ruby method lookup work?

A
  • This checks the eigenclass of foo for Singleton methods named bar.
  • If no method bar is found in the eigenclass, Ruby searches the class of foo for an instance method named bar.
  • If no method bar is found in the class, Ruby searches the instance methods of any modules included by the
    class of foo. If that class includes more than one module, they are searched in the reverse of the order in which
    they were included. That is, the most recently included module is searched first.
  • If no instance method baris found in the class of foo or in its modules, the search moves up the inheritance
    hierarchy to the superclass. Steps 2 and 3 are repeated for each class in the inheritance hierarchy until each
    ancestor class and its included modules have been searched.
  • If no method named bar is found after completing the search, a method named method_missing is invoked
    instead.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the eigenclass?

A

The eigenclassis a class created “under the hood” between an object and its class.
However, the class of this object remains the same. The eigenclassjust keeps all the
Singleton methods for this exact object. It is present is because it keeps Ruby’s method
lookup the same—Ruby still searches for the called method ”from down to up” so it
doesn’t miss Singleton methods and finds it for each object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly