Object-Oriented Programming
Since nearly everything in Ruby is an object, Ruby is definitely an object-oriented
programming language.
A class is a way of organizing and producing objects with similar attributes and methods.
This class will create new objects of class Person (just like "A" is of class String). Every
variable of an instance of a class starts with @.
The initialize method specifies the class's attributes and creates them for every class instance.
class Person
attr_accessor :name, :occupation, :age // attributes that every Person will have
def initialize(name, occupation, age) // parameters which can be called anything we want
@name = name // new Person's @name will be the data we
provide in place of the name parameter
@occupation = occupation
@age = age
end
def is_retired
if @age > 65
return true
else
return false
end
end
end
lena = Person.new("Lena Esposito", "Web Developer", 35)
puts lena.is_retired // false
puts lena.name // Lena Esposito
Variables
We use:
$ for global variables (created inside of a class but available
everywhere),
@ for instance variables (available to a particular instance of a
class),
@@ for class variables (available to all members of a certain class).
Inheritance
One class can take on the attributes and methods of another. This process ic called inheritance.
Here ClassOne inherits CLassTwo.
class ClassOne < ClassTwo
end
Super
Thanks to the keyword super we can directly access the attributes or methods of a superclass.
class Dog
def name
puts "I am a dog."
end
end
class Lab < Dog
def what_animal
super
end
end
lab = Lab.new()
lab.what_animal // I am a dog.
Public and private
In Ruby we can classify some methods as public or private. Public
methods can be called from outside of the class, private cannot.
We put the keyword public/private before out method definition.
All methods are public by default.
private
def method
code block
end
In order to access private information, we have to create public methods that know how to get it.
attr_reader, attr_writer, attr_accessor
We can use attr_reader to access a variable and attr_writer to change it. If we want to be able to use both those things we use attr_accessor.
Modules
Modules are used to group together and store a bunch of methods (written with camel case) and constants (written with all caps).
module ModuleName
bunch of methods
and CONSTANTS
end
Ruby uses double colon which is called the scope resolution operator to specify the place where it can find information. In this case we use the built-in PI costant.
puts Math::PI // 3.141592653589793
If we need methods from a module we need to require them or include them (inside a calss).
require 'date'
puts Date.today // 2023-11-20
module ModuleFive
code
end
class Class
include ModuleFive
end
The extend keyword mixes a module's methods at the class level. This means that class itself can use the methods, as opposed to instances of the class.
Comments (0)
Be the first to leave a comment