Search code examples
rubynamed-parametersoptional-arguments

Optional arguments with default value in Ruby


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?


Solution

  • You cannot do that (or something similar) in Ruby < 2.0. The best you could do is:

    def my_function(h = {})
      h[:c] ||= 500
      # Use h[:a], h[:b], h[:c]
      ...
    end
    
    my_function(b: 100)