Uvod u objektno orijentirano programiranje s Rubyjem

Kao student računarstva provodim puno vremena učeći i igrajući se s novim jezicima. Svaki novi jezik može ponuditi nešto jedinstveno. Nakon toga, većina početnika započinje svoje programsko putovanje bilo proceduralnim jezicima poput C ili objektno orijentiranim jezicima kao što su JavaScript i C ++.

Stoga ima smisla proći kroz osnove objektno orijentiranog programiranja kako biste mogli razumjeti koncepte i primijeniti ih na jezike koje lako učite. Kao primjer ćemo koristiti programski jezik Ruby.

Možda se pitate, zašto Ruby? Zato što je "dizajniran da usreći programere" i zato što je gotovo sve u Rubyju objekt.

Dobivanje osjećaja objektno orijentirane paradigme (OOP)

U OOP-u identificiramo "stvari" s kojima se naš program bavi. Kao ljudi, razmišljamo o stvarima kao o objektima s atributima i ponašanjem i komuniciramo sa stvarima na temelju tih atributa i ponašanja. Stvar može biti automobil, knjiga itd. Takve stvari postaju klase (nacrti predmeta), a mi stvaramo predmete iz tih klasa.

Svaka instanca (objekt) sadrži varijable instance koje su stanje objekta (atributa). Predmeti ponašanja predstavljeni su metodama.

Uzmimo primjer automobila. Automobil je stvar koja bi ga učinila klasom . Specifična vrsta automobila, recimo da je BMW objekt klase automobila . U atributi / svojstva za BMW kao što su boja i modela broja mogu biti pohranjeni u varijable instance. A ako želite izvršiti operaciju objekta, poput vožnje, tada "pogon" opisuje ponašanje koje je definirano kao metoda .

Lekcija brze sintakse

  • Za završetak retka u Ruby programu, točka-zarez (;) nije obavezan (ali se obično ne koristi)
  • Potiče se uvlačenje u dva razmaka za svaku ugniježđenu razinu (nije potrebno, kao u Pythonu)
  • Ne koriste se kovrčave zagrade {}, a ključna riječ end koristi se za označavanje kraja bloka kontrole protoka
  • Za komentiranje koristimo #simbol

Načini na koji se stvaraju objekti u Rubyu su pozivanjem nove metode na klasi, kao u primjeru u nastavku:

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

Da biste razumjeli što se događa u gornjem kodu:

  • Imamo klasu koja se naziva Cars dvije metode initializei get_info.
  • Varijable instance u Rubyju započinju s @(na primjer @name). Zanimljiv je dio da varijable u početku nisu deklarirane. Oni nastaju kada se prvi put koriste, a nakon toga su dostupni svim instancijskim metodama klase.
  • Pozivanje newmetode uzrokuje aktiviranje initializemetode. initializeje posebna metoda koja se koristi kao konstruktor.

Pristup podacima

Varijable instance su privatne i ne može im se pristupiti izvan klase. Da bismo im pristupili, moramo stvoriti metode. Instance metode imaju javni pristup prema zadanim postavkama. Možemo ograničiti pristup ovim metodama instance, kao što ćemo vidjeti kasnije u ovom članku.

Da bismo dobili i izmijenili podatke, trebaju nam metode "getter" i "setter". Pogledajmo ove metode uzimajući isti primjer automobila.

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

U Rubyu su "getter" i "setter" definirani istim imenom kao varijabla instance s kojom imamo posla.

U gornjem primjeru, kada kažemo my_car.color, zapravo poziva colormetodu koja zauzvrat vraća ime boje.

Napomena: Obratite pažnju na to kako Ruby dopušta da se razmak između colori jednakih potpiše dok koristite setter, iako je naziv metodecolor=

Pisanje ovih getter / setter metoda omogućuje nam veću kontrolu. Ali najčešće je dobivanje postojeće vrijednosti i postavljanje nove vrijednosti jednostavno. Dakle, trebao bi postojati lakši način umjesto da se zapravo definiraju getter / setter metode.

Lakši način

attr_*Umjesto korištenja obrasca možemo dobiti postojeću vrijednost i postaviti novu vrijednost.

  • attr_accessor: za getera i setera
  • attr_reader: samo za dobivanje
  • attr_writer: samo za postavljača

Pogledajmo ovaj obrazac uzimajući isti primjer automobila.

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

Na ovaj način možemo potpuno preskočiti definicije getera / postavljača.

Govoreći o najboljim praksama

U gornjem primjeru nismo inicijalizirali vrijednosti za varijable @nameand i @colorinstance, što nije dobra praksa. Također, kako su varijable instance postavljene na nulu, objekt car1nema nikakvog smisla. Uvijek je dobra praksa postavljanje varijabli instance pomoću konstruktora kao u donjem primjeru.

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

Metode razreda i varijable razreda

Dakle, metode klase pozivaju se na klasu, a ne na instancu klase. To su slične statičkim metodama u Javi.

Napomena: selfizvan definicije metode odnosi se na objekt klase. Varijable razreda započinju sa@@

Postoje zapravo tri načina za definiranje metoda klase u Rubyju:

Unutar definicije klase

  1. Upotreba ključne riječi self s nazivom metode:
class MathFunctions def self.two_times(num) num * 2 endend
# No instance createdputs MathFunctions.two_times(10) # => 20

2. Korištenje <<; sebe

class MathFunctions class << self def two_times(num) num * 2 end endend
# No instance createdputs MathFunctions.two_times(10) # => 20

Izvan definicije razreda

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:

  1. Specifying public, protected, or private and everything until the next access control keyword will have that access control level.
  2. 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.