Methods, blocks and sorting in Ruby

Damien Cosset - Sep 20 '18 - - Dev Community

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
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

Arguments and parameters

You can provide arguments to methods, like so:

say_hi("John")
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

Splat arguments

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

say_hi("John", "Paul", "Sarah")
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Or other methods:

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

returnsMethod(5, 6) # returns 30
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

Have fun!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .