Skip to content

Instantly share code, notes, and snippets.

@kylebragger
Created December 24, 2009 02:09
Show Gist options
  • Save kylebragger/262964 to your computer and use it in GitHub Desktop.
Save kylebragger/262964 to your computer and use it in GitHub Desktop.
#keeping it posi (oh, Patrick!)
class Hash
def keeping(keys = [])
raise 'Please specify at least one key!' if keys.empty?
strkeys = keys.collect {|k| k.to_s}
self.clone.delete_if {|k,v| !strkeys.include?(k.to_s)}
end
end
# Tests!
h = {:kyle => 'Bragger', :patrick => 'Ewing'}
puts h.keeping([:kyle]).keys == [:kyle]
h2 = {:foo => 'bar', :baz => ['lol', 'cats'], :quux => {:a => 'b', :c => 'd'}}
puts h2.keeping([:foo, :baz]).keys == [:foo, :baz]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment