Ruby Functions

A function is a group of instructions that together perform a task; it is defined once and can be used (i.e. called) as many times as needed.

Defining a function

A function is defined via the def keyword:

def say_hello_to(name) {
  puts "Hello " + name;

Using a function

Here is how to call our say_hello_to function, using "Paul" as value for the name parameter:

  Hello Paul

Mindtwisting moment: Ruby doesn't have functions

Everything in Ruby is an object, with classes being the blueprints from which objects are created.

The "functions" we created above are in fact methods, on a default, "hidden" object named main. You might have also noticed, in the code above, another "function": puts - it is another example of a main method.

Moreover, everything in your Ruby program occurs in the context of the main object, itself an instance of an Object.