Returning a value

You may have noticed in the first tutorial that all the functions outputted text the console. Perhaps you don't want to do that. Maybe you just want a function to return a value.

Every function returns a value. The value returned will be the last line of code that outputs a value. For example.

def my_function
var1 = nil
var2 = false
var3 = true
var3
end

Calling this function would return true. If we added puts my_function to the code it would output true to the console, the value of var3, which is the last line in the function.

But what if we wanted to return var1 or var2? That's where the return keyword comes in play.

def my_function
var1 = nil
var2 = false
var3 = true
return var1
end

When we call this function, we get the value of var1. We can output this to the console using puts or manipulate it in any way you want.

Variable arguments

We know that we can specify multiple arguments for a function by seperating them by commas like this: def func(arg1, arg2). But what if we don't know how many arguments our function will be taking?

That's where variable arguments comes in hand. A variable argument looks like this: *variable_name. You see that asterisk? That tells Ruby that you are specifying a variable argument. Instead of passing a single value to the function, it passes an array. Here's an example.