Skip to content

Instantly share code, notes, and snippets.

@ryanjm
Created June 26, 2012 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanjm/2999736 to your computer and use it in GitHub Desktop.
Save ryanjm/2999736 to your computer and use it in GitHub Desktop.
A little lesson in ruby methods

Methods in ruby have a special feature if the last attribute is a hash

def dashed_keys(h1, h2)
  "h1(#{ h1.keys.join("-") }) h2(#{ h2.keys.join("-") })"
end

> dashed_keys({:a => 1, :b => 2}, {:m => 13, :n => 14})
=> "h1(a-b) h2(m-n)"

You don't even need the curly brackets for the last one. You just need it for the first one so ruby knows where one hash ends and the other starts.

> dashed_keys({:a => 1, :b => 2}, :m => 13, :n => 14)
=> "h1(a-b) h2(m-n)"

Lets look at another function

def dashed_keys(h)
  h.keys.join("-")
end

If you try to call this method by itself, it will fail

> dashed_keys
ArgumentError: wrong number of arguments (0 for 1)

You can get around this with a default value

def dashed_keys(h = {})
  h.keys.join("-")
end

> dashed_keys(h)
=> ""

This is why you'll often see in Rails methods an optional hash at the end. For example see text_field.

text_field(object_name, method, options = {})

It lets you do things like:

text_field :message, :title, :id => "msg_title", :class => "red"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment