ruby methods are reusable code blocks. By calling a ruby method, all of the code in the method will be executed.

Methods should start with a lowercase character and only contain alphabetic characters.
A method can take one or more parameters which can be used in the code block.

Related course:
Learn Rails 5.2: Accelerated Web Development with Ruby on Rails

Methods in ruby

Example

The method below can be called as many times as you want: a method is reusable code.
Methods can also return output, this output can then be used in the program.

1
2
3
4
5
6
7
#!/usr/bin/ruby

def hello(x1 = "Debby")
puts "Hello #{x1}"
end
hello "Ruby"
hello

The method hello above is called with a parameter and without.
Sometimes parameters are necessary for your codeblock, but at times they are not.

The parameter in this example is x1, which is given a value outside the method.

method

Return value

A value inside a ruby method only exists there (local scope). It can be given to the program with the return statement, return x1. That then needs to be saved in an output variable.

1
2
3
4
5
6
7
8
9
#!/usr/bin/ruby

def multiply(x1 = 0, x2 = 0)
x3 = x1 * x2
return x3
end

val = multiply 2, 3
puts val

Exercises

  1. Create a method that sums two numbers
  2. Create a method that calls another method.