Declarative Keyword Parameters in Ruby (SBPP #5)

Reading SBPP has got me thinking about keyword parameters. Ruby doesn’t have keyword arguments, but it fakes them pretty well:

Which is fine, but it isn’t as declarative (and therefore not as self-documenting) as proper keyword arguments.

Also, when using keywords to construct English-like DSLs, as we are above, we often would like to assign different names to the parameters which are passed by keyword.

And then there’s defaulting for missing paramters…

Of course, it might be nice to offer a positional-argument version as well.

Once we’ve written all this parameter-munging machinery, we then repeat it in the method’s documentation. (Assuming we document it at all). This seems a bit un-DRY.

Let’s see if we can improve on the situation.

This is just an alpha-level library I banged out during RubyConf 2011, so I’m sure there are plenty of edge cases I haven’t handled. I’ll leave it to you to decide if the syntax above is an improvement or not. There’s a certain nasty “pre-ISO C functions” feel to declaring the keywords before the method definition. But I like that the acceptable parameters are obvious and not hidden in the method definition.

Of course, none of this is a substitute for real language-level keyword params, which I hear we’ll be getting in Ruby 2.0. But in the meantime, it’s something to play with.

The code is here: