Intro to Ruby - Methods

Ruby

Overview

The following demonstrates the basics of defining and using methods through the def…end keywords. There are other ways to define methods but we won’t get into that for now. You might have guessed that you can use parenthesis when defining and using a method although, generally you don’t need them. For example, the following is valid syntax:

puts “Ruby”
puts(”Ruby”)

The same goes for method definitions.

Read on to learn more about methods.

Code

# Example methods, scroll down to read more about how these methods are being used.

def print_single value
puts value
end

def print_with_default value = "Unknown"
puts value
end

def print_variables label = "Unknown", *variables
puts "#{label}: #{variables.join ', '}"
end

def print_nil
end

def multi_return
return "one", "two", "three"
end

def last_return
v = 3 * 10
"I am the return value"
end

# The following method accepts one parameter (required) and then prints it.
puts "01 Single Value\n\n"
print_single "Heya"

# The following method also accepts one parameter but it is optional.
# In this case, passing no parameter results in the default value being printed.
puts "\n02 Default Value\n\n"
print_with_default

# The following method prints a labeled, variable-length array. The label is optional
# and the array can be any length in size.
puts "\n03 Variable Length Parameters\n\n"
print_variables "My Color Picks", "red", "black", "green", "blue", "violet"

# The following method does absolutely nothing but all Ruby methods return a value and, in this case,
# we get nil as the return value.
puts "\n04 Nil Return Value\n\n"
puts print_nil

# One handy feature is the ability to return multiple values. The following method demonstrates
# having multiple values returned. If you still have the "06-variables.rb" script handy, you might
# play with this more to see how you could assign these values to multiple variables. Don't be shy, give it a try!
puts "\n05 Multi-Return Value\n\n"
puts multi_return

# As mentioned above, a method always returns a value. The following method does some calculations but only
# a string is returned because it is the last statement listed in the method. Something to keep in mind
# when you are writing your own code.
puts "\n06 Last Return\n\n"
puts last_return

Output

01 Single Value

Heya

02 Default Value

Unknown

03 Variable Length Parameters

My Color Picks: red, black, green, blue, violet

04 Nil Return Value

nil

05 Multi-Return Value

one
two
three

06 Last Return

I am the return value

Download

The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 07-methods.rb.

What’s Next

Blocks

Tags:

Thursday, February 26th, 2009 Software

No comments yet.

Leave a comment

You must be logged in to post a comment.