Home > Mobile >  Handling keyword parameters in `method_missing`
Handling keyword parameters in `method_missing`

Time:02-01

When I write method_missing in a custom class I am not sure if I can implement it def method_missing(meth, *args, **kwargs, &block) or just def method_missing(meth, *args, &block). (The docs for method_missing do not cover keyword arguments.) How are keyword parameters handled in missing_method?

(N.B. This is mentioned in a comment on the question In Ruby is there a built-in method that requires keyword arguments?, but the answer does not cover the question in the comment.)

CodePudding user response:

method_missing works just like any other method in this regard. When you use a double splat it will slurp any keyword arguments and kwargs will always be a hash:

module Foo
  def self.method_missing(*args, **kwargs, &block)
    kwargs
  end
end
irb(main):049:0> Foo.bar(baz: 'Hello World')
=> {:baz=>"Hello World"}    
  •  Tags:  
  • Related