1. Computing
Send to a Friend via Email

Methods

By

Methods

Up until now, we've just been defining methods. It seems like something everyone should know how to do. Even if you haven't learned specifically how to define methods, you've probably seen enough example code to know how it's done. You use the def keyword, give it a name and some arguments and that's about it, right?

More or less, yes, that is right. Most of what you see in example (and production) code is all there is to methods. Methods in Ruby are very simple. So here we'll go over how to define them (in case you haven't picked up on that yet) and the specifics about what they really are.

Defining Methods

Methods are defined with the def keyword. This keyword can appear at any point in the code and will define a method with the specified name, taking the specified number of arguments. If the method takes no arguments, the argument list can (and it is idiomatic to do so) be omitted. These are all examples of valid method definition.


# Method called "say_hello" with one argument called "name"
def say_hello(name)
  puts "Hello #{name}"
end

# Method with no arguments
def say_goodbye
  puts "Goodbye!"
end

# Another method with no arguments
def ask_name()
  puts "What is your name?"
  return gets.chomp
end

This is all rather straightforward, every single programming language that I know (except Commodore 64 BASIC, which used line numbers for everything) has the concept of a named container for code that takes arguments. If you're familiar with programming at all, this should be no surprise to you.

Return Values

Methods return values. They can do this with explicit return statements, which will immediately end method execution and return, or by returning the result of the last expression in the method. This is a common idiom, for single-method lines to omit the return keyword. Just remember that methods always return something even if there is no explicit return statement. Look to the last line in the method (this can be a bit hard to find if there are conditionals involved) and you will find what's being returned by the method.

Ruby methods can also return multiple values using the comma (,) operator. The calling method can catch these multiple return value by using the assignment operator with the comma operator, or using a soak operator.

All these methods return values.


def return_statement
  return true
  
  # The following line will never be reached
  puts "Unreachable"
end

def add(a,b)
  # This is the last (and only) line of the method
  # It doesn't need a return statement
  a + b
end

def split(str)
  # This returns two objects
  s = str.split(' ')

  return s[0], s[1]
end

# Split a name and assign to two variables
name = "Alice Boberton"
first, last = split(name)

Multiple Arguments

Ruby enforces arity. If a method takes three arguments, you must pass three arguments. Passing more or less will cause Ruby to raise an ArgumentError exception. But, being the flexible language that it is, allows you to use the soak operator in the method argument list.

If you use the soak operator in the method argument list, that argument will soak up as many arguments as it can. It's usually the last argument in the list (and must be on Ruby 1.8.7 and before) will appear as an array of the arguments it soaked up within the method.

The following code will say hello to as many people as you'd like.


def say_hello(*people)
  people.each do|p|
    puts "Hello #{p}"
  end
end

Calling Methods

Calling methods is rather straightforward. The widely-accepted form of method(arg1, arg2) works in Ruby. However, if there are no method arguments to pass the argument list is usually omitted (including the parentheses). Also, where it won't make things ambiguous (usually if it's the only thing on a line), the parentheses are often omitted.

If parentheses are used, they must be the first character after the method name. There can be no space between the method name and the open parenthesis.


# Call the puts method with no arguments, which
# prints a blank line
puts

# Call puts with one argument, parentheses omitted
puts "Hovercraft"

# Call with two arguments, parentheses used
puts( "I like", "ham and eggs" )

Idiomatic Method Names

Method names in Ruby are lower-case and use snake_case. No form of camelCase should be used in Ruby method names. Methods must start with a lowercase letter and can contain any characters that may be used in identifiers. Additionally, the last character of a method may be the exclamation point character (!), question mark (?) or equals sign (=). These characters cannot appear in the middle of the method name, only as the last character.

These special characters have special meaning (though often only by idiom).

  • Equals sign (=) - The method can be called as if it were an assignment statement. See Using Attributes.
  • Question Mark (?) - The method is asking a question, and should return true or false. Good example of this are Array#empty? and Object#is_a?. These are asking simple questions of the object (is the array emtpy, is the object of a certain type) and return true or false. This is just an idiom though, a method named this way can behave however it wishes.
  • Exclamation Point (!) - This is usually a "harder" or more dangerous version of a method. For example, the String#chomp method returns whitespace from the end of a string and returns a new string. However, this is slow (as the string must be copied and new memory allocated) and most of the time the programmer just wants to throw away the whitespace, so the String#chomp! method is used. This doesn't allocate a new string and modifies the string in place. It's more destructive than the original chomp method, so it gets the exclamation point to denote this. This is also just an idiom, any method can end in the exclamation point.

©2014 About.com. All rights reserved.