Extending Hash with Except and Only
Posted by Chad Humphries about 1 year ago
I first saw this on the RSpec lists, but I can't find who to originally credit.   This little extension to Hash lets you easily get only the key(s) you want out of a hash, or all but certain keys out of the hash.

class Hash
  # Usage { :a => 1, :b => 2, :c => 3}.except(:a) -> { :b => 2, :c => 3}
  def except(*keys)
    self.reject { |k,v|
      keys.include? k.to_sym
    }
  end

  # Usage { :a => 1, :b => 2, :c => 3}.only(:a) -> {:a => 1}
  def only(*keys)
    self.dup.reject { |k,v|
      !keys.include? k.to_sym
    }
  end
end
Language Ruby / Tagged with hash