Ruby Programming/Writing methods

< Ruby Programming

Method definitionEdit

A method definition is started with the def keyword and ended with the end keyword. Some programmers find the method definition notation in Ruby very similar to the one of Python.

def myMethod

To define a method that takes a parameter, you can put the name of the variable in parantheses after the method name. When the method is invoked, the code in the method will be run with a local variable with the name of the specified parameter.

def myMethod(msg)
  puts msg

If you need multiple parameters you can separate them with a comma.

def myMethod(msg, person)
  puts "Hi, my name is " + person + ". Some information about myself: " + msg

Invoking methodsEdit

You can invoke methods with or without parentheses although it can be considered bad style if you omit them, so the safe way is to always write them in the beginning until you know when it's safe to leave them away.

# With parentheses

# Without parentheses

If you want to invoke a method with parameters you need to put the parameter(s) between the brackets (or if you omit them, between the invisible brackets) and separate them with commas if there are more than one.

def myMethod(a, b)
  puts a + b

myMethod(1, 2)
myMethod 1, 2
myMethod("abc", "xyz")

You can also use the value of a variable as a parameter.

def myMethod(a)
  puts "Hello " + a

name = "World"

Default valuesEdit

Often, a method may have parameters of which many, if not all, could have clever defaults. Having to specify all of the parameters every time you invoke the method can be an inconvenience. Because of this, it's possible to define default values. This can be actually quite easily; simply assign the parameter a value in the definition. You can combine parameters with and without default values.

def myMethod(message="This is a default value")
  puts message

myMethod("Where has the default value gone?")

Returning valuesEdit

You often want a method to return a value. You can do so by using the return statement.

def myMethod
  return "Hello"

puts myMethod()

However, because Ruby developers are lazy, they developed a feature that always returns the last evaluated statement (sometimes it's a bit tricky to know which one this is). Knowing this, you can turn the above example into the following:

def myMethod

puts myMethod()

Note that a return statement finishes the execution of a method. Combined with the fact that you can return without a value this is often useful to stop a method from further execution if certain conditions are met.

def myMethod
  while true
    puts "Because the condition of this while loop is 'true' it will run forever, right?"

See alsoEdit

This page was only meant to give some introduction how to work with methods in Ruby because this is a very important concept. However there is a more detailed page about methods and some other cool things that weren't mentioned here.