Skipping extra keyword arguments in Ruby

3.4k views Asked by At

I defined a method:

def method(one: 1, two: 2)
   [one, two]
end

and when I call it like this:

method one: 'one', three: 'three'

I get:

ArgumentError: unknown keyword: three

I do not want to extract desired keys from a hash one by one or exclude extra keys. Is there way to circumvent this behaviour except defining the method like this:

def method(one: 1, two: 2, **other)
  [one, two, other]
end
3

There are 3 answers

4
sawa On BEST ANSWER

If you don't want to write the other as in **other, you can omit it.

def method(one: 1, two: 2, **)
  [one, two]
end
1
Eugene Petrov On

Not sure if it works in ruby 2.0, but you can try using **_ to ignore the other arguments.

def method(one: 1, two: 2, **_)

In terms of memory usage and everything else, I believe there's no difference between this and **other, but underscore is a standard way to mute an argument in ruby.

2
chad_ On

A common way to approach this is with an options hash. You will see this, frequently:

def method_name(opts={})
  one = opts[:one] || 1  # if caller doesn't send :one, provide a default
  two = opts[:two] || 2  # if caller doesn't send :two, provide a default

  # etc
end