I’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:
def print_name_and_age(age, name_hash) p "Name: #{name_hash[:first]} #{name_hash[:middle]} #{name_hash[:last]}" p "Age: #{age}" end print_name_and_age 25, :first=>'John', :middle=>'M.', :last=>'Smith' |

