Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing default values for method

Tags:

ruby

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)

like image 498
notme1560 Avatar asked Mar 19 '17 01:03

notme1560


People also ask

Can you assign the default values to a function parameters?

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.

Can you set default parameters in Java?

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.

How do you assign default values to variables?

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.

How do you call a function with default parameters?

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.


1 Answers

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
    
like image 53
matt Avatar answered Oct 22 '22 23:10

matt