Creating Functions in Ruby: Part II
Zavexeon (1034)

First Part

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

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 

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.

def var_func_test(*args)
  puts *args[0]
  puts *args[1]
  puts *args[2]

var_func_test("Potato", 1, true)

This outputs:


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

  1. Variables declared within a function are inaccessible outside of the function, unless the variable is a global or class variable.
  2. Functions can be put inside functions! You would call them like this: func1::func2.
  3. 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.

You are viewing a single comment. View All