Methods, blocks and sorting in Ruby
Tags: ruby
Published: 2018-09-20 18:08:12

---
title: Methods, blocks and sorting in Ruby
published: true
description: Moar basic stuff!!
cover_image: https://cl.ly/8ee24235a491/Image%202018-09-20%20at%208.14.30%20PM.png
tags: ruby
---

## Introduction

My Ruby's journey continues as I keep learning the basics of the language. This time, I explore methods, blocks and sorting. Let's see if I got it right.

## Methods

Methods are reusable pieces of code written in order to execute a certain task. Writing methods makes your code more readable, less redondant and easier to test.

### Method syntax

A method has a header and a body. The header is composed of the keyword *def* followed by the method name. The body is the piece of code that gets executed when you call a method. Finally, when you are done with the body, you use the keyword *end*, to indicates that the following code doesn't concern the method.

```ruby
def say_hi
	puts "Hi!"
end
```

Defining is all good, but we need to call the method to execute the method's body.
To call a method, use its name:

```ruby
say_hi # Hi!
```

## Arguments and parameters

You can provide arguments to methods, like so:

```ruby
say_hi("John")
```

This means that our methods must expect those arguments. You have to modify the method definition to include *parameters*. Parameters are the placeholder for an argument, while the method is waiting to be called:

```ruby
def say_hi(name) # <= name is the parameter
	puts "Hi #{name}!"
end

say_hi("John") # <= John is the argument
# Hi John!
```

### Splat arguments

What happens if we give more than one argument to our say_hi method?

```ruby
say_hi("John", "Paul", "Sarah")
```

We get the following error:
`wrong number of arguments (given 3, expected 1) (ArgumentError)`

If you don't know how many arguments a method will receive, you can use something called *splat arguments*. To tell a method that more than the number of arguments it expects, you add an * before the parameter name:

```ruby
def say_hi(*names)
	names.each{|name|
    puts "Hi #{name}!"
  }
end

say_hi("John", "Joe", "Sarah")

# Hi John!
# Hi Joe!
# Hi Sarah!
```

### Returning from a method

Printing is all fine, but most of the times, you'll need to return something from the operations executed in your method. To do that, you'll use the *return* keyword.


```ruby
def multiply(a, b)
	return a*b
end

multiply(2, 3) # returns 6
multiply(4, 5) # returns 20
```

Methods can return anything you want, not just numbers. Booleans for example:

```ruby
def isEven?(a)
	return a % 2 == 0
end

isEven?(3) # returns false
isEven?(10) # returns true
```

Or other methods:

```ruby
def returnsMethod(a, b)
	return multiply(a, b)
end

returnsMethod(5, 6) # returns 30
```

Note: The last example returns the *multiply* method which returns a number.

## Sorting

Ruby provides a built-in sort method called *sort*.

```ruby
arr = [5, 2, 3, 1, 4, 5, 3]
arr.sort! # [1, 2, 3, 3, 4, 5, 5]

#OR

new_array = arr.sort
```

Remember that adding the ! at the end of the method mutates the original variable.
You can also omit it and store the result in a new variable. Sorting works also on strings:

```ruby
movies = ["1984", "Notre-Dame de Paris", "I am a legend", "Clean Code"]
movies.sort! # ["1984", "Clean Code", "I am a legend", "Notre-Dame de Paris"]
```

### Combined comparison operator

Ruby also has an operator to compare two values called the combined comparison operator: *<=>* 

If the first value comes before the second, it returns **-1**, it returns **1** if 
# it's the contrary. Finally, it will return 0 if both items are equal.

```ruby
a = 1
b = 4

a <=> b # -1
b <=> a # 1
```
### Sorting by descending order

By default, the sort method sorts in the ascending order. You can provide a block as an optional argument to sort by descending order. You can use the combined comparison operator.

```ruby
movies.sort! {|firstMovie, secondMovie| secondMovie <=> firstMovie}
# ["Notre-Dame de Paris", "I am a legend", "Clean Code", "1984"]
```

Have fun!