I would like to create a function that has optional arguments with default values
def my_function(a = nil, b=nil, c=500)
end
and call the function with the arguments I would like to specify only
my_function(b=100)
How do I accomplish this in Ruby 1.9.2?
You cannot do that (or something similar) in Ruby < 2.0. The best you could do is:
So you're trying to implement keyword arguments? This is supposed to be a new feature in Ruby 2.0, but you can try to mimic it in 1.9.x with a hash of arguments instead. Here's a post that discusses how you can accomplish that, which gives the following code sample:
Arguments are bound to parameters like this:
Proc
and bound to the block argumentraise
anArgumentError
Here's an example:
So, as you can see both from step 3 above and from the example, you cannot do this, because optional parameters are bound left-to-right, but you want to specify the middle argument.
Note that this has implications on API design: you should design your parameter lists in such a way that the most "unstable" optional parameters, i.e. the ones that a user most likely wants to supply themselves, are furthest to the left.
Ruby 2.0 now has keyword arguments, which is exactly what you are looking for: