Link
Embed
Share
Beginning
This slide
Copy link URL
Copy link URL
Copy iframe embed code
Copy iframe embed code
Copy javascript embed code
Copy javascript embed code
Share
Tweet
Share
Tweet
Slide 1
Slide 1 text
Ruby 2.0 Keyword Arguments Ian Anderson
Slide 2
Slide 2 text
Ruby 1.9 - Hash parameters def foo(opts = {}) bar = opts.fetch(:bar, 'default') puts bar end foo # 'default' foo(bar: 'baz') # 'baz'
Slide 3
Slide 3 text
Ruby 2.0 - Keyword arguments def foo(bar: 'default') puts bar end foo # 'default' foo(bar: 'baz') # 'baz'
Slide 4
Slide 4 text
What if..? def foo(bar: 'default') puts bar end foo('baz') # ArgumentError: wrong number of arguments (1 for 0)
Slide 5
Slide 5 text
PRINCIPLE OF MOST SURPRISE
Slide 6
Slide 6 text
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}]
Slide 7
Slide 7 text
Janky required keyword arguments def foo(bar: raise(ArgumentError)) puts bar end foo # ArgumentError: ArgumentError foo(bar: 'baz') # 'baz'
Slide 8
Slide 8 text
Block keyword arguments whoooaaaa define_method(:foo) do |bar: 'baz'| puts bar end foo # 'baz' foo(bar: 'qux') # 'qux'
Slide 9
Slide 9 text
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
Slide 10
Slide 10 text
Concrete example - Ruby 2.0 def accepts_nested_attributes_for(*attr_names, allow_destroy: false, update_only: false reject_if: nil, limit: nil ) end
Slide 11
Slide 11 text
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} )
Slide 12
Slide 12 text
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
Slide 13
Slide 13 text
Try out Ruby 2.0 today!