A method with an optional parameter A method with an optional parameter ruby ruby

A method with an optional parameter


def some_func(variable = nil)  ...end


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.countendsome_func("x", nil)# 2

2. Send and receive as hash:

def some_func(**args)  puts args.countendsome_func(a: "x", b: nil)# 2


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

def print_arg(args = {})  if args.has_key?(:age)    puts args[:age]  endendprint_arg # => print_arg(age: 35, weight: 90)# => 35