0

I have method to which I want to pass an optional argument. By default I want to set that argument as nil. Here is the way I am doing it:

def my_function(arg1, arg2: nil)
  # Do something
end

I call the function as my_function(2, 5). I am getting an error which says: "wrong number of arguments (given 2, expected 1)"

Am I doing something wrong here? I wish to pass a value for arg2 during some calls and want it to be nil otherwise. So when I don't pass a value for arg2, my function call looks like my_function(2).

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
tech_human
  • 6,592
  • 16
  • 65
  • 107

2 Answers2

2

Try out

def my_function(arg1, arg2 = nil)
Ursus
  • 29,643
  • 3
  • 33
  • 50
1

You're defining a default keyword argument (vs a positional argument). You can call the function that you've defined with my_function(2) as well as my_function(2, arg2: 5). If you would like to use a positional argument you can define it as def my_function(arg1, arg2 = nil)

Here are some details on keyword arguments. https://robots.thoughtbot.com/ruby-2-keyword-arguments

Tyler Willingham
  • 539
  • 1
  • 7
  • 18