The Pug Automatic

Non-obvious method arguments in Ruby

Written February 4, 2008. Tagged Ruby.

I really dislike non-obvious method arguments in Ruby (and elsewhere).

Ruby doesn't have named arguments, but the idiom is to fake that with a hash argument:

colonel_mustard.do_it(:with => :icepick, :in => :rumpus_room)

Methods can take non-named arguments that are still pretty obvious. This is true for most one-argument methods like print. Another example is alias_method where the mnemonic is in the name – specify the alias, then the method (though a lot of people don't seem to get this).

Some methods take very non-obvious arguments, though. Module#attr takes a boolean second argument to specify whether the attribute should be writable or not. So you might do

attr :name, true

Thankfully, in many cases there are wrapper methods that abstract the non-obvious arguments into method names: in this case,

attr_accessor :name

will in effect run

attr :name, true

When there's no wrapper method, though, and you don't want to make your own, here's a tip: simply use throw-away local variables to make your code more readable. So instead of

do_cryptic_stuff(true, false, 5)

consider

do_cryptic_stuff(indefinitely = true, with_flair = false, minutes = 5)

That's it. Quite obvious, but perhaps the kind of obvious you never realize.