Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Ruby 2.0 Keyword Arguments

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers.

Ruby 2.0 Keyword Arguments

Avatar for iancanderson

iancanderson

April 04, 2013
Tweet

More Decks by iancanderson

Other Decks in Programming

Transcript

  1. Ruby 1.9 - Hash parameters def foo(opts = {}) bar

    = opts.fetch(:bar, 'default') puts bar end foo # 'default' foo(bar: 'baz') # 'baz'
  2. Ruby 2.0 - Keyword arguments def foo(bar: 'default') puts bar

    end foo # 'default' foo(bar: 'baz') # 'baz'
  3. What if..? def foo(bar: 'default') puts bar end foo('baz') #

    ArgumentError: wrong number of arguments (1 for 0)
  4. Keyword arguments + (optional) options def foo(bar, baz: 'qux', **options)

    puts [bar, baz, options] end foo(1, option: 2) # [1, 'qux', {:option => 2}] foo(1, option: 2, baz: 'notqux') # [1, 'notqux', {:option => 2}]
  5. Janky required keyword arguments def foo(bar: raise(ArgumentError)) puts bar end

    foo # ArgumentError: ArgumentError foo(bar: 'baz') # 'baz'
  6. Concrete example - Ruby 1.9 def accepts_nested_attributes_for(*attr_names) options = {

    :allow_destroy => false, :update_only => false } options.update(attr_names.extract_options!) options.assert_valid_keys( :allow_destroy, :reject_if, :limit, :update_only ) end
  7. Anatomy of a Ruby 2.0 method def foo( {required_arguments, ...}

    {optional_arguments, ...} {*rest || more_required_arguments...} {keyword_arguments: "defaults"...} {**rest_of_keyword_arguments} {&block_capture} )
  8. Method of the year. def foo(req1, req2, maybe1 = "42",

    maybe2 = maybe1.upcase, *args, named1: 'foo', named2: bar(named1, req2), **options, &block) end def bar(a, b) # ... end