
# extract_options!
The (old) “standard” way of extracting an optional options hash passed as the last parameter of a method call :
- def add_food( *args )
- options = args.last.is_a?( Hash ) ? args.pop : {}
- puts args.inspect
- puts options.inspect
- end
- add_food( "cheese", :edible => true, :drinkable => false )
- => "cheese"
- => {:edible=>true, :drinkable=>false }
This is something I’m seemingly doing more and more, and let’s face it – It’s ugly.
However, as of changeset 7217 (and the original ticket) of Rails, a method has been added to Array encapulate this. You can now do :
- require 'active_support'
- def add_food( *args )
- options = args.extract_options!
- puts args.inspect
- puts options.inspect
- end
- add_food( "cheese", :edible => true, :drinkable => false )
- => "cheese"
- => {:edible=>true, :drinkable=>false}
Such a simple addition, it’s hard to believe there wasn’t already a method to do this.
Update: And yes, I realise my examples above are crap – Hopefully you can see what’s happening though.