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
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 may include the deprecated use of options hashes with:
Hash.new("this")
in the method signature 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.