Aprendiendo Ruby: de cero a héroe

"Ruby es simple en apariencia, pero es muy complejo por dentro, al igual que nuestro cuerpo humano". - Matz, creador del lenguaje de programación Ruby

¿Por qué aprender Ruby?

Para mí, la primera razón es que es un idioma hermoso. Es natural codificar y siempre expresa mis pensamientos.

La segunda, y principal, razón es Rails : el mismo marco que utilizan Twitter, Basecamp, Airbnb, Github y tantas empresas.

Introducción / Historia

Ruby es “Un lenguaje de programación de código abierto dinámico con un enfoque en la simplicidad y la productividad. Tiene una sintaxis elegante que es natural de leer y fácil de escribir ". - ruby-lang.org

¡Comencemos con algunos conceptos básicos!

Variables

Puede pensar en una variable como una palabra que almacena un valor. Simple como eso.

En Ruby es fácil definir una variable y establecerle un valor. Imagina que quieres almacenar el número 1 en una variable llamada uno. ¡Vamos a hacerlo!

one = 1

¿Qué tan simple fue eso? Acaba de asignar el valor 1 a una variable llamada uno.

two = 2 some_number = 10000

Puede asignar un valor a cualquier variable que desee. En el ejemplo anterior, una variable de dos almacena un número entero de 2 y algún número almacena 10.000.

Además de números enteros, también podemos usar valores booleanos (verdadero / falso), cadenas, símbolos, flotantes y otros tipos de datos.

# booleans true_boolean = true false_boolean = false # string my_name = "Leandro Tk" # symbol a_symbol = :my_symbol # float book_price = 15.80

Declaraciones condicionales: flujo de control

Las declaraciones condicionales evalúan verdadero o falso. Si algo es cierto, ejecuta lo que está dentro de la declaración. Por ejemplo:

if true puts "Hello Ruby If" end if 2 > 1 puts "2 is greater than 1" end

2 es mayor que 1, por lo que se ejecuta el código de put.

Esta instrucción else se ejecutará cuando la expresión if sea falsa:

if 1 > 2 puts "1 is greater than 2" else puts "1 is not greater than 2" end

1 no es mayor que 2, por lo que se ejecutará el código dentro de la instrucción else.

También está la declaración de elsif. Puedes usarlo así:

if 1 > 2 puts "1 is greater than 2" elsif 2 > 1 puts "1 is not greater than 2" else puts "1 is equal to 2" end

Una forma en la que realmente me gusta escribir Ruby es usar una declaración if después del código que se ejecutará:

def hey_ho? true end puts "let’s go" if hey_ho?

Es tan hermoso y natural. Es idiomático Ruby.

Bucle / iterador

En Ruby podemos iterar de muchas formas diferentes. Hablaré de tres iteradores: while, for y each.

Mientras se repite: siempre que la declaración sea verdadera, se ejecutará el código dentro del bloque. Entonces este código imprimirá el número del 1 al 10:

num = 1 while num <= 10 puts num num += 1 end

For bucle: pasa la variable num al bloque y la instrucción for la repetirá por usted. Este código se imprimirá igual que el código while: de 1 a 10:

for num in 1...10 puts num end

Cada iterador: Me gusta mucho cada iterador. Para una matriz de valores, iterará uno por uno, pasando la variable al bloque:

[1, 2, 3, 4, 5].each do |num| puts num end

Es posible que se pregunte cuál es la diferencia entre cada iterador y el bucle. La principal diferencia es que cada iterador solo mantiene la variable dentro del bloque de iteración, mientras que para el bucle permite que la variable viva fuera del bloque.

# for vs each # for looping for num in 1...5 puts num end puts num # => 5 # each iterator [1, 2, 3, 4, 5].each do |num| puts num end puts num # => undefined local variable or method `n' for main:Object (NameError)

Matriz: Colección / Lista / Estructura de datos

Imagina que quieres almacenar el entero 1 en una variable. Pero tal vez ahora quieras almacenar 2. Y 3, 4, 5…

¿Tengo una forma de almacenar todos los enteros que quiero, pero no en millones de variables? ¡Ruby tiene una respuesta!

Array es una colección que se puede usar para almacenar una lista de valores (como estos enteros). ¡Así que usémoslo!

my_integers = [1, 2, 3, 4, 5]

Es realmente sencillo. Creamos una matriz y la almacenamos en my_integer .

Es posible que se pregunte: "¿Cómo puedo obtener un valor de esta matriz?" Gran pregunta. Las matrices tienen un concepto llamado índice. El primer elemento obtiene el índice 0 (cero). El segundo obtiene 1, y así sucesivamente. ¡Entiendes la idea!

Usando la sintaxis de Ruby, es simple de entender:

my_integers = [5, 7, 1, 3, 4] print my_integers[0] # 5 print my_integers[1] # 7 print my_integers[4] # 4

Imagine que desea almacenar cadenas en lugar de números enteros, como una lista de los nombres de sus familiares. El mío sería algo como esto:

relatives_names = [ "Toshiaki", "Juliana", "Yuji", "Bruno", "Kaio" ] print relatives_names[4] # Kaio

Funciona de la misma forma que los números enteros. ¡Agradable!

Acabamos de aprender cómo funcionan los índices de matriz. Ahora agreguemos elementos a la estructura de datos de la matriz (elementos a la lista).

Los métodos más comunes para agregar un nuevo valor a una matriz son push y <<.

¡Empujar es súper simple! Solo necesita pasar el elemento (The Effective Engineer) como el parámetro push:

bookshelf = [] bookshelf.push("The Effective Engineer") bookshelf.push("The 4 hours work week") print bookshelf[0] # The Effective Engineer print bookshelf[1] # The 4 hours work week

El método << es ligeramente diferente:

bookshelf = [] bookshelf << "Lean Startup" bookshelf << "Zero to One" print bookshelf[0] # Lean Startup print bookshelf[1] # Zero to One

You may ask, “But it doesn’t use the dot notation like other methods do. How could it be a method?” Nice question! Writing this:

bookshelf << "Hooked"

…is similar to writing this:

bookshelf.<<("Hooked")

Ruby is so great, huh?

Well, enough arrays. Let’s talk about another data structure.

Hash: Key-Value Data Structure/Dictionary Collection

We know that arrays are indexed with numbers. But what if we don’t want to use numbers as indices? Some data structures can use numeric, string, or other types of indices. The hash data structure is one of them.

Hash is a collection of key-value pairs. It looks like this:

hash_example = { "key1" => "value1", "key2" => "value2", "key3" => "value3" }

The key is the index pointing to the value. How do we access the hash value? Using the key!

Here’s a hash about me. My name, nickname, and nationality are the hash’s keys.

hash_tk = { "name" => "Leandro", "nickname" => "Tk", "nationality" => "Brazilian" } print "My name is #{hash_tk["name"]}" # My name is Leandro print "But you can call me #{hash_tk["nickname"]}" # But you can call me Tk print "And by the way I'm #{hash_tk["nationality"]}" # And by the way I'm Brazilian

In the above example I printed a phrase about me using all the values stored in the hash.

Another cool thing about hashes is that we can use anything as the value. I’ll add the key “age” and my real integer age (24).

hash_tk = { "name" => "Leandro", "nickname" => "Tk", "nationality" => "Brazilian", "age" => 24 } print "My name is #{hash_tk["name"]}" # My name is Leandro print "But you can call me #{hash_tk["nickname"]}" # But you can call me Tk print "And by the way I'm #{hash_tk["age"]} and #{hash_tk["nationality"]}" # And by the way I'm 24 and Brazilian 

Let’s learn how to add elements to a hash. The key pointing to a value is a big part of what hash is — and the same goes for when we want to add elements to it.

hash_tk = { "name" => "Leandro", "nickname" => "Tk", "nationality" => "Brazilian" } hash_tk["age"] = 24 print hash_tk # { "name" => "Leandro", "nickname" => "Tk", "nationality" => "Brazilian", "age" => 24 } 

We just need to assign a value to a hash key. Nothing complicated here, right?

Iteration: Looping Through Data Structures

The array iteration is very simple. Ruby developers commonly use the each iterator. Let’s do it:

bookshelf = [ "The Effective Engineer", "The 4 hours work week", "Zero to One", "Lean Startup", "Hooked" ] bookshelf.each do |book| puts book end

The each iterator works by passing array elements as parameters in the block. In the above example, we print each element.

For hash data structure, we can also use the each iterator by passing two parameters to the block: the key and the value. Here’s an example:

hash = { "some_key" => "some_value" } hash.each { |key, value| puts "#{key}: #{value}" } # some_key: some_value

We named the two parameters as key and value, but it’s not necessary. We can name them anything:

hash_tk = { "name" => "Leandro", "nickname" => "Tk", "nationality" => "Brazilian", "age" => 24 } hash_tk.each do |attribute, value| puts "#{attribute}: #{value}" end

You can see we used attribute as a parameter for the hash key and it works properly. Great!

Classes & Objects

As an object oriented programming language, Ruby uses the concepts of class and object.

“Class” is a way to define objects. In the real world there are many objects of the same type. Like vehicles, dogs, bikes. Each vehicle has similar components (wheels, doors, engine).

“Objects” have two main characteristics: data and behavior. Vehicles have data like number of wheels and number of doors. They also have behavior like accelerating and stopping.

In object oriented programming we call data “attributes” and behavior “methods.”

Data = Attributes

Behavior = Methods

Ruby Object Oriented Programming Mode: On

Let’s understand Ruby syntax for classes:

class Vehicle end

We define Vehicle with class statement and finish with end. Easy!

And objects are instances of a class. We create an instance by calling the .new method.

vehicle = Vehicle.new

Here vehicle is an object (or instance) of the class Vehicle.

Our vehicle class will have 4 attributes: Wheels, type of tank, seating capacity, and maximum velocity.

Let’s define our class Vehicle to receive data and instantiate it.

class Vehicle def initialize(number_of_wheels, type_of_tank, seating_capacity, maximum_velocity) @number_of_wheels = number_of_wheels @type_of_tank = type_of_tank @seating_capacity = seating_capacity @maximum_velocity = maximum_velocity end end

We use the initialize method. We call it a constructor method so when we create the vehicle object, we can define its attributes.

Imagine that you love the Tesla Model S and want to create this kind of object. It has 4 wheels. Its tank type is electric energy. It has space for 5 seats and a maximum velocity is 250km/hour (155 mph). Let’s create the object tesla_model_s! :)

tesla_model_s = Vehicle.new(4, 'electric', 5, 250)

4 wheels + electric tank + 5 seats + 250km/hour maximum speed = tesla_model_s.

tesla_model_s # =>

We’ve set the Tesla’s attributes. But how do we access them?

We send a message to the object asking about them. We call it a method. It’s the object’s behavior. Let’s implement it!

class Vehicle def initialize(number_of_wheels, type_of_tank, seating_capacity, maximum_velocity) @number_of_wheels = number_of_wheels @type_of_tank = type_of_tank @seating_capacity = seating_capacity @maximum_velocity = maximum_velocity end def number_of_wheels @number_of_wheels end def set_number_of_wheels=(number) @number_of_wheels = number end end

This is an implementation of two methods: number_of_wheels and set_number_of_wheels. We call it “getter” and “setter.” First we get the attribute value, and second, we set a value for the attribute.

In Ruby, we can do that without methods using attr_reader, attr_writer and attr_accessor. Let’s see it with code!

  • attr_reader: implements the getter method
class Vehicle attr_reader :number_of_wheels def initialize(number_of_wheels, type_of_tank, seating_capacity, maximum_velocity) @number_of_wheels = number_of_wheels @type_of_tank = type_of_tank @seating_capacity = seating_capacity @maximum_velocity = maximum_velocity end end tesla_model_s = Vehicle.new(4, 'electric', 5, 250) tesla_model_s.number_of_wheels # => 4
  • attr_writer: implements the setter method
class Vehicle attr_writer :number_of_wheels def initialize(number_of_wheels, type_of_tank, seating_capacity, maximum_velocity) @number_of_wheels = number_of_wheels @type_of_tank = type_of_tank @seating_capacity = seating_capacity @maximum_velocity = maximum_velocity end end # number_of_wheels equals 4 tesla_model_s = Vehicle.new(4, 'electric', 5, 250) tesla_model_s # =>  # number_of_wheels equals 3 tesla_model_s.number_of_wheels = 3 tesla_model_s # =>
  • attr_accessor: implements both methods
class Vehicle attr_accessor :number_of_wheels def initialize(number_of_wheels, type_of_tank, seating_capacity, maximum_velocity) @number_of_wheels = number_of_wheels @type_of_tank = type_of_tank @seating_capacity = seating_capacity @maximum_velocity = maximum_velocity end end # number_of_wheels equals 4 tesla_model_s = Vehicle.new(4, 'electric', 5, 250) tesla_model_s.number_of_wheels # => 4 # number_of_wheels equals 3 tesla_model_s.number_of_wheels = 3 tesla_model_s.number_of_wheels # => 3

So now we’ve learned how to get attribute values, implement the getter and setter methods, and use attr (reader, writer, and accessor).

We can also use methods to do other things — like a “make_noise” method. Let’s see it!

class Vehicle def initialize(number_of_wheels, type_of_tank, seating_capacity, maximum_velocity) @number_of_wheels = number_of_wheels @type_of_tank = type_of_tank @seating_capacity = seating_capacity @maximum_velocity = maximum_velocity end def make_noise "VRRRRUUUUM" end end

Cuando llamamos a este método, simplemente devuelve una cadena "VRRRRUUUUM".

v = Vehicle.new(4, 'gasoline', 5, 180) v.make_noise # => "VRRRRUUUUM"

Encapsulación: Ocultar información

La encapsulación es una forma de restringir el acceso directo a los datos y métodos de los objetos. Al mismo tiempo, facilita la operación sobre esos datos (métodos de objetos).

La encapsulación se puede utilizar para ocultar los miembros de datos y la función de los miembros ... La encapsulación significa que la representación interna de un objeto generalmente está oculta a la vista fuera de la definición del objeto.

- Wikipedia

Entonces, toda la representación interna de un objeto está oculta desde el exterior, solo el objeto puede interactuar con sus datos internos.

En Ruby utilizamos métodos para acceder directamente a los datos. Veamos un ejemplo:

class Person def initialize(name, age) @name = name @age = age end end

Acabamos de implementar esta clase Person. Y como hemos aprendido, para crear el objeto persona, usamos el nuevo método y pasamos los parámetros.

tk = Person.new("Leandro Tk", 24)

So I created me! :) The tk object! Passing my name and my age. But how can I access this information? My first attempt is to call the name and age methods.

tk.name > NoMethodError: undefined method `name' for #

We can’t do it! We didn’t implement the name (and the age) method.

Remember when I said “In Ruby we use methods to directly access data?” To access the tk name and age we need to implement those methods on our Person class.

class Person def initialize(name, age) @name = name @age = age end def name @name end def age @age end end

Now we can directly access this information. With encapsulation we can ensure that the object (tk in this case) is only allowed to access name and age. The internal representation of the object is hidden from the outside.

Inheritance: behaviors and characteristics

Certain objects have something in common. Behavior and characteristics.

For example, I inherited some characteristics and behaviors from my father — like his eyes and hair. And behaviors like impatience and introversion.

In object oriented programming, classes can inherit common characteristics (data) and behavior (methods) from another class.

Let’s see another example and implement it in Ruby.

Imagine a car. Number of wheels, seating capacity and maximum velocity are all attributes of a car.

class Car attr_accessor :number_of_wheels, :seating_capacity, :maximum_velocity def initialize(number_of_wheels, seating_capacity, maximum_velocity) @number_of_wheels = number_of_wheels @seating_capacity = seating_capacity @maximum_velocity = maximum_velocity end end

Our Car class implemented! :)

my_car = Car.new(4, 5, 250) my_car.number_of_wheels # 4 my_car.seating_capacity # 5 my_car.maximum_velocity # 250

Instantiated, we can use all methods created! Nice!

In Ruby, we use the < operator to show a class inherits from another. An ElectricCar class can inherit from our Car class.

class ElectricCar < Car end

Simple as that! We don’t need to implement the initialize method and any other method, because this class already has it (inherited from the Car class). Let’s prove it!

tesla_model_s = ElectricCar.new(4, 5, 250) tesla_model_s.number_of_wheels # 4 tesla_model_s.seating_capacity # 5 tesla_model_s.maximum_velocity # 250

Beautiful!

Module: A Toolbox

We can think of a module as a toolbox that contains a set of constants and methods.

An example of a Ruby module is Math. We can access the constant PI:

Math::PI # > 3.141592653589793 

And the .sqrt method:

Math.sqrt(9) # 3.0

And we can implement our own module and use it in classes. We have a RunnerAthlete class:

class RunnerAthlete def initialize(name) @name = name end end

And implement a module Skill to have the average_speed method.

module Skill def average_speed puts "My average speed is 20mph" end end

How do we add the module to our classes so it has this behavior (average_speed method)? We just include it!

class RunnerAthlete include Skill def initialize(name) @name = name end end

See the “include Skill”! And now we can use this method in our instance of RunnerAthlete class.

mohamed = RunnerAthlete.new("Mohamed Farah") mohamed.average_speed # "My average speed is 20mph"

Yay! To finish modules, we need to understand the following:

  • A module can have no instances.
  • A module can have no subclasses.
  • A module is defined by module…end.

Wrapping Up!

We learned A LOT of things here!

  • How Ruby variables work
  • How Ruby conditional statements work
  • How Ruby looping & iterators work
  • Array: Collection | List
  • Hash: Key-Value Collection
  • How we can iterate through this data structures
  • Objects & Classes
  • Attributes as objects’ data
  • Methods as objects’ behavior
  • Using Ruby getters and setters
  • Encapsulation: hiding information
  • Inheritance: behaviors and characteristics
  • Modules: a toolbox

That’s it

Congrats! You completed this dense piece of content about Ruby! We learned a lot here. Hope you liked it.

Have fun, keep learning, and always keep coding!

My Twitter & Github. ☺