Functions and Recursion

Function definition

Functions are useful when writing code because you can reuse code without rewriting it every time you need it. Functions are defined with three components: header, parameters, and body.

  • Header – includes the def keyword, the name of the function, and parameters required by the function
  • Parameters – also called arguments; what the function needs to do work (i.e. numbers, words, etc.); there can be as many parameters as you need for your function to do the job it is given
  • Body – can include comments to help explain what the function is doing; the body is indented, like if/elsif/else-statements
  • End – you must include the end keyword to end your function
Calling a function
After defining a function, it must be called to be implemented. If you do not call your function, it cannot do the work it was designed for.

Example:

say_hello(“Jen”)

name = “Noor”
say_hello(name)
 

Functions can be useful for simple things such as printing text or completing simple arithmetic problems. They can also be used for much more powerful tasks. For example, a function can call another function and a function can call itself. When a function calls itself, this is called recursion.

 Function calling another function

 

 Recursion

 

   
Practice what you’ve just learned!
Download the file “Functions.rb” below. Open the file with Notepad++ and follow the instructions to complete the program