In a method that accepts several optional parameters, how can you specify any other than the first?

I have a way like this:

def foo(fruit='apple', cut="sliced", topping="ice cream") # some logic here end 

How can I call it where I only redefine the topping parameter but use the default values ​​for others, something like this

 foo('','','hot fudge') 

Of course, this does not work properly, but I only want to provide a value for the third optional parameter and have the first two sticks with their default values. I know how to do this with a hash, but is this a shortcut for this using the syntax above?

+7
ruby
source share
3 answers

You cannot use this syntax for this in ruby. I would recommend hash syntax for this.

 def foo(args={}) args[:fruit] ||= 'apple' args[:cut] ||= 'sliced' args[:topping] ||= 'ice cream' # some logic here end foo(:topping => 'hot fudge') 

You can also do this with positional arguments:

 def foo(fruit=nil,cut=nil,topping=nil) fruit ||= 'apple' cut ||= 'sliced' topping ||= 'ice cream' # some logic here end foo(nil,nil,'hot fudge') 

Keep in mind that both of these methods prevent the passing of actual nil arguments to functions (whenever you want sometimes)

+17
source share

Like Ruby 2.0, you can use keyword arguments:

 def foo(fruit: 'apple', cut: "sliced", topping: "ice cream") [fruit, cut, topping] end foo(topping: 'hot fudge') # => ['apple', 'sliced', 'hot fudge'] 
+15
source share

Not. You should check the value of the parameters inside the foo function. If it is an empty string or null, you can set them by default.

+2
source share

All Articles