Methods, blocks and sorting in 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.

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:

say_hi # Hi!

Arguments and parameters

You can provide arguments to methods, like so:

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:

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?

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:

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.

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:

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

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

Or other methods:

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.

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:

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.

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.

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

Have fun!

Your email address will not be published. Required fields are marked *

*