In Ruby, we use methods throughout programs. Iterators are built with methods. We find methods on classes (instance methods) and at the top level of programs.
Methods are a form of structured programming. They provide easily-reusable blocks of code. With these blocks, we construct more complex logical models.
Here we use a method. It accepts one parameter of identifier "value." It returns a value, the result of an expression evaluation—the argument is multiplied by 100.
calculate()
method with an argument of 2.def calculate(value) # Multiply by 100 and return. return value * 100 end # Call calculate method. result1 = calculate(5) result2 = calculate(10) result3 = calculate(calculate(2)) # Print results. print result1, "\n" print result2, "\n" print result3, "\n"500 1000 20000
Ruby supports default values for parameters. We assign to the parameters within the method definition. Here, the compute method has two parameters. And both have default values.
def compute(width = 10, height = 10) # Uses default values for parameters if not specified. return width * height end # 5 times 5. puts compute(5, 5) # 5 times 10. puts compute(5) # 10 times 10. puts compute25 50 100
An implicit return value is one that is not specified. In Ruby, the last expression evaluated is used as a return value. So we can avoid typing the "return" keyword.
def test(x, y) # This expression is evaluated and returned. (x * 10) + y end # Call test with two arguments. result = test 5, 10 # Display the result. # ... (5 * 10) + 10 = 60 puts result60
We can call methods with keyword arguments. To call a method with a keyword, the method def must have the keywords specified in its declaration.
def display(name: "?", id: 0, size: 0) # Display all keyword arguments. print "Name: ", name, "\n" print "Id: ", id, "\n" print "Size: ", size, "\n" end # Call method with keyword arguments. display(id: 10, size: 5, name: "cat")Name: cat Id: 10 Size: 5
A method can receive a variable number of arguments. We use a star before the argument name. And that argument becomes an array that stores as many parameters as needed.
def test(*items) # Iterate over the elements in the array. items.each do |item| puts item end end # Call with three arguments. test("abc", "def", "ghi")abc def ghi
A method can be aliased with the alias keyword. When the alias is called, the original method is invoked. This works like a macro. Sometimes using an alias can make code clearer.
def method() puts "Hello" end # Alias the identifier "m" to "method" alias m method # Call method. m()Hello
Ruby supports the BEGIN and END blocks. If we want to ensure some statements run at start or exit time, these statements are useful. They must be in all capital letters.
# Code in BEGIN is run before anything else. BEGIN { puts(1) } # Code in END is run afterwards. END { puts(2) } # This is after BEGIN and before END. puts "Middle"1 Middle 2
The "defined?" and undef methods test to see if a method has been defined. We can use defined in an if
-statement to see if a method can be invoked.
def test() puts "Hello world" end # The test method is now defined. if defined?(test) puts true end # Undefine the method. undef test # The method is no longer defined. if !defined?(test) puts false endtrue false
An empty method returns nil
. It has no statements, so the evaluation result of the last statement cannot be returned.
# This empty method returns nil. def test end # Test return value of method. if test() == nil puts true endtrue
We create programs that do nontrivial things, that solve problems. With "defined?" we test whether a method is defined. With recursion we create brute-force solvers.