61

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
sawa
  • 165,429
  • 45
  • 277
  • 381
TamRock
  • 1,490
  • 1
  • 11
  • 27

3 Answers3

109
def some_func(variable = nil)
  ...
end
sawa
  • 165,429
  • 45
  • 277
  • 381
20

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
bogl
  • 1,864
  • 1
  • 15
  • 32
  • what is the purpose of using `*arg` and `**arg` instead of just `arg`? – Sagar Pandya Mar 02 '16 at 13:47
  • 7
    @sagarpandya82 `*arg` collects the arguments as an array. Without the `*` you would have to call `some_func(["x", nil])`. `**arg` collects all named arguments. Without the `**` it would only accept either a single unnamed argument, or any number of named arguments. – bogl Mar 02 '16 at 14:07
11

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
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
Charmi
  • 594
  • 1
  • 5
  • 20