Ruby on Rails Course 2009

Ruby: Methods

Normal method call:

method_name(parameter1, parameter2)

Sometimes there is no need for parenthesis:

method_name
results = method_name parameter1, parameter2

And sometimes you really need them:

results = method_name(parameter1, parameter2).reverse

Defining a Method

def output_something(value)
  puts value
end

Return Values

Methods return the value of the last statement executed. The following code returns the value x+y.

def sum(x, y)
  x + y
end

Explicit Return

An explicit return statement can also be used to return from a function, if necessary:

def authenticate(username)
  return unless username == "bob"
  puts "Welcome, Bob!"
end

Default Values

Default parameter values are used when the parameter is not specified, or is nil.

def greet(username="anonymous")
  puts "Hello " + username + "!"
end