Skip to content

Instantly share code, notes, and snippets.

@IanVaughan
Created June 26, 2012 23:22
Show Gist options
  • Select an option

  • Save IanVaughan/3000099 to your computer and use it in GitHub Desktop.

Select an option

Save IanVaughan/3000099 to your computer and use it in GitHub Desktop.
Ruby, hashes, and default params

I was surprised by where my params were going with a call to a method with defaulted hash parameters.

So I tested it in IRB, and here are the results.

Create test program

def test(a, h1={}, h2={})
  pp a
  pp h1
  pp h2
end

Just pass first param, leave second to default

> test 1, :foo=>'bar'
1
{:foo=>"bar"}
{}

Same, but create explicit hash-literal

> test 1, {:foo=>'bar'}
1
{:foo=>"bar"}
{}

Pass both hash params, both explicit hashes. Works as expected.

> test 1, {:foo=>'bar'}, {:tee=>'fee'}
1
{:foo=>"bar"}
{:tee=>"fee"}

Same, but 2nd as a single parameter. Ruby will see no more elements, and create a hash for this.

> test 1, {:foo=>'bar'}, :tee=>'fee'
1
{:foo=>"bar"}
{:tee=>"fee"}

Same again, but 1st as a single parameter. Error.

> test 1, :foo=>'bar', {:tee=>'fee'}
SyntaxError: (irb):46: syntax error, unexpected '\n', expecting tASSOC

Now, two params passed in, both implicate single element hashes :-

test 1, :foo=>'bar', :tee=>'fee'
1
{:foo=>"bar", :tee=>"fee"}
{}

Ruby sees the second param, and greedily merges that into the first hash!

Watch out for this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment