More Advanced Ruby Method Arguments – Hashes And Block Basics

ArgumentsI’ve previously given an overview of basic method arguments in Ruby (at least in Ruby 1.9). There is quite a lot you can do with just the basic method arguments, so I purposely left out the more advanced topics from that post (which many people were quick to point out :)). However, if you want to have an in-depth knowledge of Ruby you will need to know how to use hashes as method arguments as well as where blocks fit into the picture and this is what I am going to cover here.

Using Hashes As Arguments

A Hash is just a regular object in Ruby, so normally, using it as an argument is no different from using any other object as an argument e.g.:

def some_method(a, my_hash, b)
  p a
  p my_hash
  p b
end
 
some_method "Hello", {:first=>"abc", :second=>"123"},"World"

This would produce the following output:

"Hello"
{:first=>"abc", :second=>"123"}
"World"

The interesting things about hashes as arguments is that depending on their location in the argument list you can get some interesting benefits (and sometimes interesting detriments).

Hashes As The Last Argument

When you use a hash as the last argument in the list Ruby allows you to forego the use of the curly braces which surprisingly can make argument lists look a lot nicer, consider this:

Method Arguments In Ruby

ArgumentMethod arguments in Ruby are interesting because of the great flexibility in how you’re allowed to supply them to methods. Ruby method arguments can loosely be broken up into two categories, required arguments and optional arguments. However, I like to break them up into three categories (I hope it will become clear by the end of this post why I do so):

  • required arguments
  • arguments with default values
  • optional arguments

Required Arguments

These are just your stock standard method arguments, e.g.:

def some_method(a, b)
end

To call the method above you will need to supply two arguments to the method call, e.g.:

some_method(25,"hello")

Pretty basic stuff, nothing much to see here, moving on :).

Arguments With Default Value

In Ruby you can supply a default value for an argument. This means that if a value for the argument isn’t supplied, the default value will be used instead, e.g.:

def some_method(a, b, c=25)
end

You may call the method above in one of two ways:

some_method(25,"hello")

or