Classes and Objects Flashcards
How to see all instance variables for the instance of a class?
.instance_variables
class Hello
def initialize
@sample = 2
end
end
Hello.new.instance_variables #=> [@sample]
What is the difference between supper and super() ?
super -> call superclass method with params from the method by default
super() -> calls methods without params
How to see all possible methods of the object?
.methods
class Hello
def hello
end
end
Hello.new.methods #=> [:hello, …]
What is self
?
will show the same object
It’s a current object. An instance of the class inside the clas
class MyClass
def first_method
puts “Current instance within first_method: #{self}”
end
end
my_object = MyClass.new
puts “my_object refers to this object: #{my_object}”
my_object.first_method
When we must use the method self explicitly inside the class?
When you try to assign local values with the same name as a method
class MyClass
def first_method
a = 10
# self.a #=>’hello’
end
def a
‘hello’
end
end
my_object = MyClass.new
my_object.first_method
# => 10
How to see all the ancestors of the class in the right order?
=> [Class, Module, Object, Kernel, BasicObject]
Class.ancestors
How to make an existing method private?
private :method_name
How to make an existing class method private?
private_class_method :new
What is the base ruby class?
class Object < BasicObject
include Kernel
end
What is the class of class?
something like this
Class.class # => Class
class Class
end
Example = Class.new
instance_of_class = Example.new
instance_of_class.class # => Example
How to find what modules are included in a class?
Class.included_modules
# [Kernel]
What returns .singleton_methods on the class?
This method returns all class methods
class Animal
def self.test
end
end
p Animal.singleton_methods
# [:test]
The singleton class is like an “empty shell”, used only for the purpose of holding onto methods, it lives between the object itself & the object’s class.
What are the differences between prepend and include module?
Prepend overrides class methods
module Hello
def hello
p ‘from module’
end
end
class Name
prepend Hello
def hello
p ‘from class’
end
end
Name.new.hello
# from module
What happens if you define the same class twice but with different methods?
class Hello
def x
‘x’
end
end
class Hello
def y
‘y’
end
end
hello = Hello.new
p hello.x # x
p hello.y # y
They extend each other
Is it possible to assign class name to variables?
class Hello
def say
p ‘a’
end
end
hello = Hello
a = hello.new
a.say