Learn to divide a program into functions or subprograms in Ruby.
Method
We can divide a program into procedural components or modules called methods in Ruby. We are already familiar with functions like print()
, get()
, step()
and length()
. Methods can be copied and reused in a programming technique called the modular or procedural approach, also known as the divide and conquer approach. We should always try to design methods that can be reused in other programs too.
Broadly, there are two types of methods, which we’ll explore in the following sections.
Structure of a method
The following slides illustrate various parts of a method definition:
A method name can only contain letters (
A
–Z
anda
–z
) and the underscore symbol (_
). It may also contain digits (0
–9
), but the function name can’t start with those. For example,Key_2
is a valid function name, but2_key
is not. Function names are case-sensitive, meaning thatname
,Name
, andNAME
are three different methods.
There are three main parts of a method definition:
- Header: This is the first line containing