Given the method:
def foo(a,b=5,c=1)
return a+(b*c)
end
Running foo(1)
should return 6
. However, how would you go about doing something like this: foo(1,DEFAULT,2)
. I need to change the third value, but use the default second value.
How would you do this? (Note: I can't just change the order of the variables because they are arguments for a method from a gem)
Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.
Short answer: No. Fortunately, you can simulate them. Many programming languages like C++ or modern JavaScript have a simple option to call a function without providing values for its arguments.
The OR Assignment (||=) Operator The logical OR assignment ( ||= ) operator assigns the new values only if the left operand is falsy. Below is an example of using ||= on a variable holding undefined . Next is an example of assigning a new value on a variable containing an empty string.
If a function with default arguments is called without passing arguments, then the default parameters are used. However, if arguments are passed while calling the function, the default arguments are ignored.
You can't do it, in the terms posed. This sort of situation is exactly why named (keyword) parameters were introduced in Ruby 2. But your parameters with default values, according to the terms of the question, are not named.
Therefore, they are positional — that is why the optional parameters must come last — and the rule is, accordingly, that this method must be called with at least one argument (because a
is not optional), and any further arguments will be used in the order supplied to fill in the corresponding parameters.
Thus, you can supply a
, or a
and b
, or a
and b
and c
. You cannot supply a
and c
alone, as you could easily do if these parameters were named.
Two obvious solutions spring to mind.
Call the method, supplying the default value of the second parameter as the second argument. Presumably you know what it is, so it's not much of a hardship:
foo(1,5,2)
Write a trampoline method that does the same thing, but where the parameters are named:
def foo(a,b=5,c=1)
return a+(b*c)
end
def bar(a,b:5,c:1)
return foo(a,b,c)
end
bar(1,c:2) # => 11
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With