Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass optional named arguments in Ruby 2.0

Tags:

ruby

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
like image 988
Kris Avatar asked Oct 27 '14 15:10

Kris


1 Answers

Probably the best way to go would be:

def bar(name: nil)
  name ||= 'unknown'
  puts name
end
like image 184
BroiSatse Avatar answered Sep 29 '22 11:09

BroiSatse