简体   繁体   中英

Is it possible to specify a default value for all parameters simultaneously in a function?

If I have a function like this:

def foo(a="this", b="this", c="this")
end

Is there some option to set a default value for all of them at the same time? Something like:

def foo(DEFAULT="this", a, b, c)
end

Metaprogramming Local Variables

If you're trying to create positional method-local variables that can be overridden, you can use a bit of metaprogramming using the current Binding . For example:

def foo a=nil, b=nil, c=nil
  %i[a b c].map do |v|
    binding.local_variable_get(v) ||
    binding.local_variable_set(v, "this")
  end
  [a, b, c]
end

This will do what you seem to want. For example:

foo 1
#=> [1, "this", "this"]

foo 1, 2
#=> [1, 2, "this"]

Other Approaches

Other approaches may include the deprecated use of options hashes with:

  • an options hash using Hash.new("this") in the method signature
  • a Hash#default= defined inside the body of the method
  • the use of Hash#fetch to return a default value when reading your options hash

If your goal is just to DRY up your code, it may be better to consider keyword arguments (eg def foo **kwargs ) rather than positional arguments, but your mileage may vary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM