Optional Curly Braces in Ruby Method Arguments: Simplicity or Confusion?

July 13, 2012

Understanding Why Curly Braces Are Optional In Rails Helper Methods

In my last post, I talked about adding a tag within an html link tag via the rails link_to helper method. But this post focuses on why when you call certain helper methods in Rails, the curly braces are optional.

If you look at the Rails framework documentation, you’ll see that the purpose of the link_to method is to create an html link tag. One common usage of link_to follows this syntax as shown in the Rails docs:

link_to(body, url, html_options = {})

Example Usage

link_to "Click me", object_path, :class => "my_css_class", :id => "my_css_id"

In actuality, the last two options are part of the html_options hash, and we could have rewritten the example link_to syntax this way:

link_to "Click me", object_path, { :class => "my_css_class", :id =>  "my_css_id" }

But Rubyists seem to prefer pith, and so leave the hashes off.

Why does this work?

It’s because of the way Ruby treats hashes as method arguments. If you call a method such that the last argument in the method’s argument list is a hash, Ruby doesn’t require you to write the hash with curly braces.

Yes, this might be considered a trivial point

But it can make your method argument list look a bit nicer than it otherwise would.

The flip side is that no braces can also make you forget that you’re passing a hash as a method argument.

Having spent a little time programming in C++, I just find this to be an interesting feature of Ruby.

What do other folks think of this? Confusing or beautiful?


Profile picture

Written by Bruce Park who lives and works in the USA building useful things. He is sometimes around on Twitter.