Skip to content

Instantly share code, notes, and snippets.

@hoverbird
Forked from kylebragger/gist:262964
Created December 24, 2009 02:16
Show Gist options
  • Save hoverbird/262968 to your computer and use it in GitHub Desktop.
Save hoverbird/262968 to your computer and use it in GitHub Desktop.
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