options snippets

Keyword arguments in Ruby +2.1

Tagged argument, keyword, options, ruby  Languages ruby

Before keyword arguments were introduced in Ruby:

def call(options={})
  puts options[:optional_param]
  puts options.fetch(:optional_param_with_default, 'default')
  puts options.fetch(:mandatory_param)
end

After:

def call(mandatory_param:, optional_param: nil, optional_param_with_default: 'default')
  puts optional_param
  puts optional_param_with_default
  puts mandatory_param
end

Mixing arguments and keywords in Ruby

Tagged arguments, keywords, options, ruby, splat  Languages ruby

Mixing arguments and keywords in Ruby:

def hello(*args, **keywords)
  { args: args, keywords: keywords }
end

Splat to the rescue:

* turns all arguments into an array.

** turns all keyword arguments into a hash.

This allows you to do the following:

hello(:one, :two, { three: :four })
# or, simply
hello(:one, :two, three: :four)

=> {:args=>[:one, :two], :keyword_args=>{:three=>:four}}

Readability is improved by using proper names:

def hello(name, **options)
  { name: name, options: options }
end