Functions in Ruby
Tags: ruby, tutorial, codenewbie, beginners
Published: 2020-11-24 16:05:56

# Welcome  
Welcome back dear readers, coders, and guests! This time we are going to go through functions and how to use them in our beloved Ruby!
First of all, we have to underline that it is with the help of functions that we can reduce thousands of lines of code to maybe hundreds or tens or even less. They let us decrease code size, optimize it, and simplify.
Depending on the situation we can use so-called **“built-in functions”** or **”user-defined functions“**. We will mainly focus on the **“user-defined-functions”** in this article.  
***
# What is a function?
  
They can be called building blocks of large programs. They let us simplify large blocks of repetitive code. By naming them correspondingly, we can call them later in any part of the program. Without them, we would have to write the same block of code many times within the program.  
  
To cut it short, a function is a named block of code. Let’s dive a little deeper in the details:
* **_A function has a unique name_**;
* **_A function can get input data_**;
* **_A function can return a value_**.  

**A function and a procedure**: The word **‘function’** actually comes from maths. If we pay attention to a function in maths, they always return a result. Because of this, in earlier programming languages, some blocks of code were called **“a function”**, and some **“a procedure”**, depending on whether it returns a result or not. You can look for it in **“Pascal”** programming language. But in modern programming languages, the difference smoothly disappeared and now they are all called functions.  
  
**Input data**: Depending on what you are trying to achieve, you sometimes need initial data to calculate something or perform some kind of operations. For instance:  

* _You need the guest's name to say hello to him by his name_;
* _You need monthly income and expenditure reports to find out whether the company is doing good_;
* _You need quantity and unit prices of products to calculate weekly sale report in a store._
  
The same logic works in programming. You sometimes need some kind of initial data to calculate something. We call them **“parameters”**.  
  
When we call a function and pass them initial data that we previously called **“parameters”** while defining the function, are now called **“arguments”**. When we list initial data while defining a function, they are called **“parameters”**. And when we list the initial data while calling the function, they are called **“arguments”**.  
  
**Output/result**: As we already mentioned above, some code blocks return a result, and some don’t. We generally use **“return”** reserved worked (keyword) to return a result from the function.  
  
***
  
# Function Examples
  
We need to use the **'def'** keyword to define a function in Ruby.  
Now let’s see some blocks of code about how to define functions:  
  
```ruby
# No input data, no output
def say_hello
   puts "Hello Ruby"
end

say_hello()  # "Hello Ruby"
```
The function above does not accept input and does not return the output result. Now, let’s give it an input data:
  
```ruby
# Gets input data but no returns no output
def say_hello(guest_name)
   puts "Hello #{guest_name}"
end

say_hello("John")  # "Hello John"
```
  
Now let’s make it accept input and return a result:
  
```ruby
# Accepts input and returns an output
def say_hello(guest_name)
   return "Hello #{guest_name}"
end

say_hello("John")  # Nothing appears on the screen

# To display the result on the screen,
# we have to pass the output result to 
# 'puts' function
puts say_hello("John")  # "Hello John" is displayed on the screen.
```
  
As we see in the last example, **‘guest_name’** is a parameter, and **‘John’** is an argument.
  
***
  
# Parameters/Arguments and output result
  
If we are providing multiple data to the function, we list them and separate them with the help of a comma. The most important part is that we have to list them in the same order when we are calling the function, as we listed them when defining the function. If we first provided the first name and then the last name, we list them in the same order when calling the function, first name, and then the last name. For example:
  
```ruby
def say_hello(first_name, last_name, age)
   puts "Hello #{first_name} #{last_name}, You are #{age} years old"
end

say_hello("John", "Brown", 25)
# "Hello John Brown, You are 25 years old"

say_hello(18, "John", "Brown")
# "Hello 18 John, You are Brown years old"
# In this example, the argument order is wrong.
```
  
In strictly typed programming languages, together with the parameter name, you provide its type. Be it an **‘integer’**, a **‘string’**, a **‘character’**, or a **‘boolean’**, you will have to indicate it together with the parameter name. In some programming languages, a compiler warns or returns an error when the wrong type of parameters are provided to the function.
  
In modern programming languages like **“Ruby”**, **“Python”** and etc., you don’t have to provide types with parameter names. It’s on the shoulders of the developer to provide the right type of data to the function.
  
We don’t always return a result from a function. But when we do, we usually use the **‘return’** keyword. But in Ruby, the last part of the function block is returned as a result. It is surely a savior for the programmer. But not all the Ruby programmers get used to it and they continue using the **‘return’** keyword to return a result. Here is a sample code:
  
```ruby
def print_bill(unit_price, quantity)
   return unit_price*quantity
end

# 4 items sold with price 3.5 USD.
puts print_bill(3.5, 4) 
# Output is '14.0'.

def print_bill_2(unit_price, quantity)
   "lala lala"
   unit_price*quantity
end

# 4 items with unit price 3.5 are sold.
puts print_bill_2(3.5, 4)
#  Output is '14.0'
# The last line has 'unit_price*quantity', so it is the result.
```
  
***
  
# “Built-in” functions
  
To make developers’ life easier, all programming languages have ready to use built-in functions. With the help of them, we can write code faster. It would have been a disaster without them.  

All the programming languages have built-in methods/functions for maths calculations and to operate on Strings. Let’s look at some of them:  
  
```ruby
# Make all characters capital - 'capitalize'
"hello".capitalize  # "HELLO"

# Converts data to string - 'to_s'
25.to_s  # "25"

# Returns the square root of a given number - 'sqrt'
Math.sqrt(25)  # 5
```
  
There are tons of built-in functions/methods like the ones we have just mentioned. Their number depends on the programming language. You can take a look at them on the official documentation web pages of the corresponding programming languages.
  
***
  
#The End
  
Finally, we are at the end of the article about functions in Ruby. It means, later on, our code will be shorter, simpler, more productive, and more professional. It adds beauty at the same time. So, never stop learning and optimizing, refining, and refactoring your code. Move one step further by learning something new every other day. Goodbye for now. Good Luck!