Omitting extra keyword arguments in Ruby

I have 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 don't want to extract the keys I want from the hash one at a time, or exclude additional keys. Is there a way to get around this behavior other than defining a method like this:

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

      

+3


source to share


3 answers


If you don't want to write other

like in **other

, you can omit it.



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

      

+7


source


Not sure if it works in ruby ​​2.0, but you can try using **_

to ignore other arguments.

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

      



As far as memory usage and everything else goes, I believe there is no difference between this and **other

, but underlining is the standard way to mute in ruby.

+2


source


A common way of approach is to use an options hash. You will see this often:

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

      

0


source







All Articles