Space Vatican

Ramblings of a curious coder

Keyword Surprises

I love keyword arguments. No more excuses for methods with too many positional parameters and say goodbye to all the awkward hash wrangling code that was needed when using optional hashes as poor man’s keyword arguments

Ruby 2.0 didn’t allow for mandatory keyword arguments. You could fake it by doing something like

1
2
def some_method required: (raise ArgumentError,"you must pass a value for required ")
end

As with normal default values, the default values provided by keyword arguments can be any ruby expression you want.

Ruby 2.1 added mandatory keyword arguments with the following syntax (which some will tell you is a bit ungainly:

1
2
def some_method required:, optional: 1
end

Knowing this, what would you expect

1
2
3
4
5
6
def some_method required:
  "hello world"
  puts required
end

some_method

to do? It certainly looks like it should raise an error because I haven’t passed the required keyword argument. However ruby actually interprets the expression on the next line as being the default argument for the keyword.

This has been fixed for future versions of ruby (See the issue). In the mean time you can avoid this by parenthesizing your function definitions

1
2
def some_method(required:)
end

which I think looks neater anyway.