Using Ruby hashes as keyword arguments, with easy defaults
The only downside to doing this is you lose out on easily setting default values using Ruby's default method argument values. You might use code something similar to the following to make up for this:
def some_method(opts={}) my_foo = opts[:foo] || 'mydefaultfoo' end
However, as you have more and more keyword options, setting defaults in this way gets rather tedious. Fortunately, Ruby's Hash#merge comes to our rescue (almost) - it allows you to merge the contents of one hash with another. The only problem - any duplicate keys in the hash you are merging will overwrite your original hash values - when it comes to setting default values, we want this to work the other way around; we only want values in the defaults hash to be merged if they do not exist in the original hash. Again, Ruby comes to our rescue - Hash#merge takes a block as an argument and will pass any duplicate values that crop up into the block - we can use this block to decide which value to keep.
Using the simple monkey patch to the Hash class below, you will no longer have to set each default individually:
class Hash def with_defaults(defaults) self.merge(defaults) { |key, old, new| old.nil? ? new : old } end def with_defaults!(defaults) self.merge!(defaults) { |key, old, new| old.nil? ? new : old } end end
Of course, sticking with Ruby naming conventions, with_defaults() will return a new hash whilst with_defaults!() will change the original hash directly.
See http://www.lukeredpath.co.uk/index.php/2006/07/27/using-ruby-hashes-as-keyword-arguments-with-easy-defaults/ for further discussion and alternatives.