Is there a way for an argument to be truly optional so I know if it was set by caller or not?
Having an argument use nil
as the default does not work because there is no way to know if the caller passed nil
or it is the default value for the argument.
Before named arguments, in Ruby 1.9, using an options hash:
def foo(options = {})
# …
bar(options)
end
def bar(options = {})
puts options.fetch(:name, ‘unknown’) # => 'unknown'
end
With Ruby 2.0 named arguments:
def foo(name: nil)
# …
bar(name: name)
end
def bar(name: ‘unknown’)
# …
puts name # => nil, since nil is explicitly passed from `foo`
end
Probably the best way to go would be:
def bar(name: nil)
name ||= 'unknown'
puts name
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With