Functions — part 1
What is a function?
From Wikipedia…
“In computer programming, a [function] is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed.”
Are functions the same as methods?
While many programmers use the terms function and method interchangeably, there is a distinction, at least in the context of object-oriented programming. A method is a function that belongs to an object, and can be called on that object, typically using dot notation. If we want to call a method on an object, then that method must be defined within the class to which that object belongs.
In the example below, the leftmost part of the code, "arthur"
, is our object — a String. The rightmost part of the code, capitalize
, is our method. The parentheses directly to the right of the method name indicate that we are calling (ie. invoking, executing, running) our method, and not simply referring to it. Instead of being called as a free-standing function, this is being called on our object, using a dot.
"arthur".capitalize()
Conversely, the code below this paragraph will result in an error. The capitalize
method has been defined inside the String class, and can therefore only be called on String type objects.
capitalize("Arthur")
You might come across other terms for functions, including (but not necessarily limited to) subroutine, routine, process, procedure, subprogram, or callable unit. These different terms may be used to indicate a subtly different type of function, they may be the preferred term in a particular programming language, or you may simply find them in books or papers written during the early days of computer programming, when there was a less uniform vocabulary in use.
What are arguments and parameters?
A parameter is a kind of local variable, used within the definition of a function, to refer to objects (or other pieces of data) that will be passed, as input, to the function when it is called.
When a function is called, and objects are passed into it, we refer to those objects as arguments.
The number of parameters a function has, and therefore the number of arguments it expects to receive, is called its arity.
def greet(name)
"Hello #{name}, nice to meet you!"
end
In the example above we are defining a function called greet
. Our function as an arity of 1— we’ve given it one parameter, which means that it must receive one argument when it is called. If we attempt to call our function with too many or too few arguments, we will receive an error.
greet("Zaphod")
In the next bit of code, above this paragraph, we are calling our function and passing it the String "Zaphod"
as an argument. This will result in the following String being returned:
"Hello Zaphod, nice to meet you!"