Method Params in Ruby

29 Apr 2009 – Denver, CO

Couple of things: firstly, I was a little fed-up trying to keep the format of code when I pasted it into this blog, and Gist and Pastie felt like overkill (although I do like those services, especially Pastie). From my github RSS feed there seemed to be a lot of activity on Jekyll so I was browsing the README and chanced upon the fact that it supports Pygment which was just what I needed. One quick python easy_install and I was up and running. Sweet!

So, I spent some time this evening looking at methods & params in Ruby (actually: here). Heres the short and sweet:

Hashes

Passing a Hash to a method will result in those parameters being rolled up into a single Hash Variable.

 
>> def accept(var)
>> var.inspect
>> end
=> nil
>> accept('a')
=> "\"a\""
>> accept('a' => 1)
=> "{\"a\"=>1}"
>> accept('a'=>1,'b'=>2)
=> "{\"a\"=>1, \"b\"=>2}"

Asterisk

An asterisk (the ‘splat’ operator) can be used on last parameter of a method to pass additional params. Additional params are collected into an array in the last parameter.

 
>> def accept2(a, b, *c)
>> c.inspect
>> end
=> nil
>> accept2(1, 2, 3, 4, 5)
=> "[3, 4, 5]"

And the reverse is true, an array parameter can be prefixed by asterisk to be expanded as its passed to the method.

 
>> a = [1, 2, 3]
=> [1, 2, 3]
>> accept2(*a)
=> "[3]"

Ampersand

Much like asterisk, except you are telling the method that a code block will be passed in. A proc object will be created and assigned to the param name.

 
>> def accept3(&code)
>> code.call
>> end
=> nil
>> accept3 {puts "philly"}
philly
=> nil