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)"
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"