A method with an optional parameter

RubyMethods

Ruby Problem Overview


Is there a way to make a method that can accept a parameter, but can also be called without one, in which case the parameter is regarded nil like the following?

some_func(variable)

some_func

Ruby Solutions


Solution 1 - Ruby

def some_func(variable = nil)
  ...
end

Solution 2 - Ruby

Besides the more obvious option of parameters with default values, that Sawa has already shown, using arrays or hashes might be handy in some cases. Both solutions preserve nil as a an argument.

1. Receive as array:

def some_func(*args)
  puts args.count
end

some_func("x", nil)
# 2

2. Send and receive as hash:

def some_func(**args)
  puts args.count
end

some_func(a: "x", b: nil)
# 2

Solution 3 - Ruby

You can also use a hash as argument and have more freedom:

def print_arg(args = {})
  if args.has_key?(:age)
    puts args[:age]
  end
end

print_arg 
# => 
print_arg(age: 35, weight: 90)
# => 35

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTamRockView Question on Stackoverflow
Solution 1 - RubysawaView Answer on Stackoverflow
Solution 2 - RubyboglView Answer on Stackoverflow
Solution 3 - RubyCharmiView Answer on Stackoverflow