Array#extract_options!

Tuesday, September 11

Rails (really, ActiveSupport) now sports a nifty new addition to Array to encapsulate the pattern of getting an options hash out of a variable number of arguments: extract_options!

If the last item in an array is a Hash, extract_options! removes and returns it. Otherwise, it just returns an empty Hash. This is primarily useful when you have a method that accepts a variable number of arguments (*args), the last of which is to be a hash of options. This is a common idiom in the Rails source code.

def options(*args)
  args.extract_options!
end

options # => {}
options(:name => 'foo', :format => 'text') # => { :name => 'foo', :format => 'text' }

This is cleaner than the way this is normally done:

def options(*args)
  options = args.last.is_a?(Hash) ? args.last : {}
end

You gotta love ActiveSupport.

Comments

Leave a response