[Skip To Content]


# extract_options!

The (old) “standard” way of extracting an optional options hash passed as the last parameter of a method call :

  1. def add_food( *args )
  2. options = args.last.is_a?( Hash ) ? args.pop : {}
  3. puts args.inspect
  4. puts options.inspect
  5. end
  6. add_food( "cheese", :edible => true, :drinkable => false )
  7. => "cheese"
  8. => {: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 :

  1. require 'active_support'
  2. def add_food( *args )
  3. options = args.extract_options!
  4. puts args.inspect
  5. puts options.inspect
  6. end
  7. add_food( "cheese", :edible => true, :drinkable => false )
  8. => "cheese"
  9. => {: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.

More about this site...

Last Week’s Top 5 Albums (More »)

  1. The SinglesThe Bluetones
  2. Night on My SideGemma Hayes
  3. PlansDeath Cab for Cutie
  4. Slipway FiresRazorlight
  5. Brain Thrust MasteryWe Are Scientists