Sage-Code Laboratory
index<--

Ruby Methods

A method is a named block of code that can be called multiple times. Other languages have functions, procedures or routines, but in Ruby has methods.  In other words a method is a bunch of statements or expressions.

Create a method

Ruby has weird stuff going on with methods that I will explain one by one later. First let’s see the simple stuff that is comprehensible and comfortable to learn.

  1. First of all a method is always defined with keyword: "def". There is no "method" keyword,
  2. Second, a method has a lowercase name. Don’t start wit capital letters ever,
  3. A method can be called by just mention its name as a statement,
  4. A method can have parameters bu this is optional,
  5. A method is a block of code so it must be finalized with "end".

Example:

#!/usr/bin/ruby
$VERBOSE = false

# define method
def method
  print "variable = ", $variable.to_s, "\n"
end

# test sub-routine
$variable = 10 # global variable
method

# second test
$variable = 20 # same global variable
method

Notes:

Method names

I have mention that method names must start with a lowercase letter? It is possible to start with underscore.  In ruby, starting something with underscore means it is not used yet. If you design a function that is not used you start with underscore. In Python if you start a variable with underscore, that variable is private.

Some predefined Ruby methods can have suffix "?". This kind of function is a "query" method. It is usually getting something as a result. For example "include?" is such a method. 

Some predefined Ruby methods can have suffix "!". That means the method is dangerous. For example a method that mutate an object could use "!" suffix. 

Some methods that you define are using "=" suffix can be used as "attribute writers". These are known as "setter methods" in other languages. They are used to make an attribute into a class writable.

If you start a method with uppercase, you may get away with it, but the program will think that it is a constant. So you can’t execute it properly if it has no parameters. If you use () after the name, it will work. 

Homework: Open the example live and run it: simple method

Method parameters

A method can have parameters, defined in a classic way, the same as in Python. Parameter names are using lowercase letters and can have initial value. You must enclose all parameters in round brackets and separate them using comma: (_ , _ , _ , …)

Optional parameters:

#!/usr/bin/ruby
$VERBOSE = false

# define method with optional parameter c
def add(a, b, c = 0)
  return a + b + c
end

# test add method
puts "1+2",   add(1,2)     # 3
puts "1+2+3", add(1,2,3) # 6
puts "1+3+2", add(a = 1, c = 3, b = 2) # 6

Notes:

Homework: open this example and run it live: ruby parameters

Variable arguments

Ruby like Python is using the same notation for variable number of arguments. This is a technique to enable capturing multiple optional argument values into a single parameter that is a collection of values.

Var args:

# define method for median (average)
def avg(a, b, *args)
  return (a + b + args.sum) / (2.0 + args.length)
end

# test avg method
print "(1+2)/2     = ",   avg(1,2), "\n" # 1.5
print "(1+2+3)/3   = ",avg(1,2,3),  "\n" # 2.0
print "(3+3+3+3)/4 = ",avg(3,3,3,3),"\n" # 3.0

Notes:

Splat operator

Similar to role of "*" in front of a parameter, you can use same operator to transform one array into its elements, one by one. You can use this technique to pass parameters to a method that require variable arguments, or to any method.

Example:

# define method for median (average)
def avg(*args)
  return args.sum / args.length.to_f
end

# create test data using input
array = []
puts "enter numbers > 0, or 0 to finish ..."
begin
   print ":"
   b = gets.to_i
   array << b if b > 0  # append b to   
end until b == 0;   

#test avg method using splat: (*) operator
print "\naverage of ", array ," is ", avg(*array)

Notes:

  1. in this example we introduce new operator "<<" called sometimes "shovel",
  2. the "array" variable is an Array that you build step by step until you enter "0",
  3. the splat operator "*" is used in the last statement

Homework: run this example live two times: splat operator

Next article: classes is cumming soon.


Boolean methods

In Ruby there is a curious notation for naming methods that return a boolean value. Method name is terminated with question mark. Such methods can be used in logical expressions.

Examples:

# range inclusion
(1..5).include?(5)  # true
(1...5).include?(5) # false

# array inclusion
[1,2,3].include?(5) #false
[1,2,3].include?(1) #true

# equality
a = 1, b = 1.0
a == b    #true
a.eql?(b) #false

# check if defined
defined?(foo) == nil #true  (foo is not defined)
defined?(a)   == nil #false (a is defined)

Note: Sometimes a function can return nil value.This symbol signify "nothing". In Python a similar value is "Null". You can compare something with nil using "==" relation operator. 

Read next: Blocks