
Informatikus hallgatóként sok időt töltök azzal, hogy új nyelveket tanuljak és játsszam. Minden új nyelv kínál valami egyedülállóat. Ennek ellenére a legtöbb kezdő programozási útját olyan eljárási nyelvekkel kezdi, mint a C, vagy olyan objektum-orientált nyelvekkel, mint a JavaScript és a C ++.
Ezért van értelme végigmenni az objektum-orientált programozás alapjain, hogy megértsük a fogalmakat és alkalmazzuk azokat a könnyen megtanult nyelvekre. Példaként a Ruby programozási nyelvet fogjuk használni.
Lehet, hogy azt kérdezi, miért Ruby? Mert „célja a programozók boldoggá tétele”, és azért is, mert a Ruby-ban szinte minden egy tárgy.
Az objektum-orientált paradigma (OOP) megismerése
Az OOP-ban meghatározzuk azokat a „dolgokat”, amelyeket programunk kezel. Emberként gondolkodunk a dolgokról, mint objektumokról, amelyek tulajdonságokkal és viselkedéssel bírnak, és ezen tulajdonságok és viselkedés alapján kölcsönhatásba lépünk a dolgokkal. A dolog lehet autó, könyv stb. Az ilyen dolgok osztályokká (tárgyak tervrajzává) válnak, és ezekből az osztályokból objektumokat hozunk létre.
Minden példány (objektum) tartalmaz példányváltozókat, amelyek az objektum (attribútumok) állapota. Az objektum viselkedését módszerek képviselik.
Vegyünk egy autó példáját. Az autó olyan dolog, amely osztályzattá tenné . Egy meghatározott típusú autó, mondjuk a BMW az autó osztályának tárgya . A BMW tulajdonságai / tulajdonságai , például a színe és a modellszáma például változókban tárolhatók. És ha azt szeretnénk, hogy valamely művelet az objektum, mint a vezetés, majd a „drive” olyan magatartás, amely a meghatározás szerint a módszer .
Gyors szintaxis lecke
- A Ruby program sorának befejezéséhez a pontosvessző (;) opcionális (de általában nem használatos)
- Javasoljuk, hogy minden beágyazott szintre 2-tagú behúzás kerüljön (nem szükséges, mint a Pythonban)
- Nem
{}
használnak göndör zárójelet , és a vég kulcsszóval jelölik az áramlásszabályozó blokk végét - A hozzászóláshoz a
#
szimbólumot használjuk
Az objektumok létrehozásának módja a Ruby-ban egy új módszer meghívásával történik egy osztályon, az alábbi példában leírtak szerint:
class Car def initialize(name, color) @name = name @color = color end
def get_info "Name: #{@name}, and Color: #{@color}" endend
my_car = Car.new("Fiat", "Red")puts my_car.get_info
Annak megértése, hogy mi történik a fenti kódban:
- Van egy osztályunk, amelyet
Car
két módszerrel nevezünk el,initialize
ésget_info
. - A Ruby példányváltozói a következőkkel kezdődnek:
@
(Például@name
). Az érdekes rész az, hogy a változókat nem kezdetben deklarálják. Létrejönnek, amikor először használják, és ezt követően az osztály összes példánymódszere számára elérhetők. - A
new
metódus meghívása a metódusinitialize
meghívását okozza .initialize
egy speciális módszer, amelyet konstruktorként használnak.
Hozzáférés az adatokhoz
A példányváltozók privátok, és nem érhetők el az osztályon kívülről. Ahhoz, hogy hozzájuk férjünk, módszereket kell létrehoznunk. A példánymódszerek alapértelmezés szerint nyilvános hozzáféréssel rendelkeznek. Korlátozhatjuk ezeknek a példányos módszereknek a hozzáférését, amint azt a cikk későbbi részében láthatjuk.
Az adatok megszerzéséhez és módosításához „getter” és „setter” módszerekre van szükségünk. Nézzük meg ezeket a módszereket, ugyanezt a példát véve egy autóra.
class Car def initialize(name, color) # "Constructor" @name = name @color = color end
def color @color end
def color= (new_color) @color = new_color endend
my_car = Car.new("Fiat", "Red")puts my_car.color # Red
my_car.color = "White"puts my_car.color # White
A Ruby-ban a „getter” és a „setter” ugyanazzal a névvel van meghatározva, mint a példányváltozó, amellyel foglalkozunk.
A fenti példában, amikor azt mondjuk my_car.color
, valójában a color
metódust hívja meg, amely viszont visszaadja a szín nevét.
Megjegyzés: Figyeljen arra, hogy a Ruby hogyan teszi lehetővé az és az egyenlő közötti szóköz aláírását a szetter használata közben, annak ellenére, hogy a metódus nevecolor
color=
Ezeknek a getter / setter módszereknek a megírása lehetővé teszi számunkra, hogy nagyobb ellenőrzést élvezzünk. De legtöbbször a meglévő érték megszerzése és új érték beállítása egyszerű. Tehát a getter / setter módszerek tényleges meghatározása helyett egy egyszerűbb módszert kell használni.
A könnyebb út
attr_*
Ehelyett az űrlap használatával megszerezhetjük a meglévő értéket, és új értéket állíthatunk be.
attr_accessor
: mind a getterhez, mind a szetterhezattr_reader
: csak a getterhezattr_writer
: csak a szetterhez
Nézzük meg ezt az űrlapot, ugyanazzal a példával, mint egy autó.
class Car attr_accessor :name, :colorend
car1 = Car.newputs car1.name # => nil
car1.name = "Suzuki"car1.color = "Gray"puts car1.color # => Gray
car1.name = "Fiat"puts car1.name # => Fiat
Így teljesen kihagyhatjuk a getter / setter definíciókat.
Beszélünk a legjobb gyakorlatokról
A fenti példában nem inicializáltuk az @name
és a @color
példány változók értékeit , ami nem jó gyakorlat. Továbbá, mivel a példányváltozók nulla értékre vannak állítva, az objektumnak car1
semmi értelme. Mindig jó gyakorlat a példányváltozók beállítása konstruktor segítségével, az alábbi példában leírtak szerint.
class Car attr_accessor :name, :color def initialize(name, color) @name = name @color = color endend
car1 = Car.new("Suzuki", "Gray")puts car1.color # => Gray
car1.name = "Fiat"puts car1.name # => Fiat
Osztálymódszerek és osztályváltozók
Tehát az osztály metódusait egy osztályra hívják fel, nem egy osztály példányára. Ezek hasonlóak a Java statikus módszereihez.
Megjegyzés: self
a metóduson kívül a definíció az osztály objektumra vonatkozik. Az osztályváltozók kezdődnek@@
Az osztálymódszerek definiálására a Ruby-ban valójában három módszer létezik:
Az osztálymeghatározás belsejében
- Az én kulcsszó használata a módszer nevével:
class MathFunctions def self.two_times(num) num * 2 endend
# No instance createdputs MathFunctions.two_times(10) # => 20
2. Használata <<
; maga
class MathFunctions class << self def two_times(num) num * 2 end endend
# No instance createdputs MathFunctions.two_times(10) # => 20
Az osztály meghatározásán kívül
3. Using class name with the method name
class MathFunctionsend
def MathFunctions.two_times(num) num * 2end
# No instance createdputs MathFunctions.two_times(10) # => 20
Class Inheritance
In Ruby, every class implicitly inherits from the Object class. Let’s look at an example.
class Car def to_s "Car" end
def speed "Top speed 100" endend
class SuperCar < Car def speed # Override "Top speed 200" endend
car = Car.newfast_car = SuperCar.new
puts "#{car}1 #{car.speed}" # => Car1 Top speed 100puts "#{fast_car}2 #{fast_car.speed}" # => Car2 Top speed 200
In the above example, the SuperCar
class overrides the speed
method which is inherited from the Car
class. The symbol &
lt; denotes inheritance.
Note: Ruby doesn’t support multiple inheritance, and so mix-ins are used instead. We will discuss them later in this article.
Modules in Ruby
A Ruby module is an important part of the Ruby programming language. It’s a major object-oriented feature of the language and supports multiple inheritance indirectly.
A module is a container for classes, methods, constants, or even other modules. Like a class, a module cannot be instantiated, but serves two main purposes:
- Namespace
- Mix-in
Modules as Namespace
A lot of languages like Java have the idea of the package structure, just to avoid collision between two classes. Let’s look into an example to understand how it works.
module Patterns class Match attr_accessor :matched endend
module Sports class Match attr_accessor :score endend
match1 = Patterns::Match.newmatch1.matched = "true"
match2 = Sports::Match.newmatch2.score = 210
In the example above, as we have two classes named Match
, we can differentiate between them and prevent collision by simply encapsulating them into different modules.
Modules as Mix-in
In the object-oriented paradigm, we have the concept of Interfaces. Mix-in provides a way to share code between multiple classes. Not only that, we can also include the built-in modules like Enumerable
and make our task much easier. Let’s see an example.
module PrintName attr_accessor :name def print_it puts "Name: #{@name}" endend
class Person include PrintNameend
class Organization include PrintNameend
person = Person.newperson.name = "Nishant"puts person.print_it # => Name: Nishant
organization = Organization.neworganization.name = "freeCodeCamp"puts organization.print_it # => Name: freeCodeCamp
Mix-ins are extremely powerful, as we only write the code once and can then include them anywhere as required.
Scope in Ruby
We will see how scope works for:
- variables
- constants
- blocks
Scope of variables
Methods and classes define a new scope for variables, and outer scope variables are not carried over to the inner scope. Let’s see what this means.
name = "Nishant"
class MyClass def my_fun name = "John" puts name # => John end
puts name # => Nishant
The outer name
variable and the inner name
variable are not the same. The outer name
variable doesn’t get carried over to the inner scope. That means if you try to print it in the inner scope without again defining it, an exception would be thrown — no such variable exists
Scope of constants
An inner scope can see constants defined in the outer scope and can also override the outer constants. But it’s important to remember that even after overriding the constant value in the inner scope, the value in the outer scope remains unchanged. Let’s see it in action.
module MyModule PI = 3.14 class MyClass def value_of_pi puts PI # => 3.14 PI = "3.144444" puts PI # => 3.144444 end end puts PI # => 3.14end
Scope of blocks
Blocks inherit the outer scope. Let’s understand it using a fantastic example I found on the internet.
class BankAccount attr_accessor :id, :amount def initialize(id, amount) @id = id @amount = amount endend
acct1 = BankAccount.new(213, 300)acct2 = BankAccount.new(22, 100)acct3 = BankAccount.new(222, 500)
accts = [acct1, acct2, acct3]
total_sum = 0accts.each do |eachAcct| total_sum = total_sum + eachAcct.amountend
puts total_sum # => 900
In the above example, if we use a method to calculate the total_sum
, the total_sum
variable would be a totally different variable inside the method. That’s why sometimes using blocks can save us a lot of time.
Having said that, a variable created inside the block is only available to the block.
Access Control
When designing a class, it is important to think about how much of it you’ll be exposing to the world. This is known as Encapsulation, and typically means hiding the internal representation of the object.
There are three levels of access control in Ruby:
- Public - no access control is enforced. Anybody can call these methods.
- Protected - can be invoked by objects of the defining classes or its sub classes.
- Private - cannot be invoked except with an explicit receiver.
Let’s see an example of Encapsulation in action:
class Car def initialize(speed, fuel_eco) @rating = speed * comfort end
def rating @rating endend
puts Car.new(100, 5).rating # => 500
Now, as the details of how the rating is calculated are kept inside the class, we can change it at any point in time without any other change. Also, we cannot set the rating from outside.
Talking about the ways to specify access control, there are two of them:
- Specifying public, protected, or private and everything until the next access control keyword will have that access control level.
- Define the method regularly, and then specify public, private, and protected access levels and list the comma(,) separated methods under those levels using method symbols.
Example of the first way:
class MyClass private def func1 "private" end protected def func2 "protected" end public def func3 "Public" endend
Example of the second way:
class MyClass def func1 "private" end def func2 "protected" end def func3 "Public" end private :func1 protected :func2 public :func3end
Note: The public and private access controls are used the most.
Conclusion
These are the very basics of Object Oriented Programming in Ruby. Now, knowing these concepts you can go deeper and learn them by building cool stuff.
Don’t forget to clap and follow if you enjoyed! Keep up with me here.