rubyargumentsruby-2.0ruby-2.1

Can I have required named parameters in Ruby 2.x?


Ruby 2.0 is adding named parameters, like this:

def say(greeting: 'hi')
  puts greeting
end

say                     # => puts 'hi'
say(greeting: 'howdy')  # => puts 'howdy'

How can I use named parameters without giving a default value, so that they are required?


Solution

  • There is no specific way in Ruby 2.0.0, but you can do it Ruby 2.1.0, with syntax like def foo(a:, b:) ...

    In Ruby 2.0.x, you can enforce it by placing any expression raising an exception, e.g.:

    def say(greeting: raise "greeting is required")
      # ...
    end
    

    If you plan on doing this a lot (and can't use Ruby 2.1+), you could use a helper method like:

    def required
      method = caller_locations(1,1)[0].label
      raise ArgumentError,
        "A required keyword argument was not specified when calling '#{method}'"
    end
    
    def say(greeting: required)
      # ...
    end
    
    say # => A required keyword argument was not specified when calling 'say'