Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a method that take multiple optional parameters, how can any but the first be specified?

Tags:

ruby

I have a method like this:

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

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

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

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

like image 328
Scott Miller Avatar asked Mar 29 '09 21:03

Scott Miller


3 Answers

As of 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']
like image 146
sheldonh Avatar answered Oct 23 '22 17:10

sheldonh


You can't use this syntax to do this in ruby. I would recommend the 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 could also do this using 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')

Bear in mind that both of these techniques prevent you from passing actual nil arguments to functions (when you might want to sometimes)

like image 25
rampion Avatar answered Oct 23 '22 17:10

rampion


No. You have to check the value of the parameters inside function foo. If they are the empty string, or null, you can set them to the default parameter.

like image 2
mpen Avatar answered Oct 23 '22 16:10

mpen