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
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.
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.
def var_func_test(*args) puts *args puts *args puts *args end var_func_test("Potato", 1, true)
Potato 1 true
What the function is doing with
*args is storing all of the info given in an array. The array for this function would look like
["Potato", 1, true].
Some things to note
- Variables declared within a function are inaccessible outside of the function, unless the variable is a global or class variable.
- Functions can be put inside functions! You would call them like this:
- You can create a default value for parameters. Like this:
def func(var1 = true). Now the function will automatically set var1 to true unless you set it to something else in the calling.
Thanks for reading my tutorial. I hope it helped. Perhaps a part III might make it's way out.