Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove keys in hash not in array

Tags:

ruby

hash

I can't find a way to remove keys from a hash that are not in a given array of key names. I read that I can use except or slice, but how can I feed them a list of the key names I want to keep? So for example, if I had this hash:

entry = {:title=>"casablanca", :media=>"dvd", :localeLanguage=>"en", :imdb=>"", :freebase=>"", :originalTitle => 'casablanca', :season=> '1', :episode => '3'}

and I only wanted to keep, say, :title, :media and :localeLanguage, how could I keep only those values whose key names I specify?

like image 882
kakubei Avatar asked Oct 12 '12 12:10

kakubei


2 Answers

In Rails 4+, use slice:

entry = {:title=>"casablanca", :media=>"dvd", :localeLanguage=>"en", :imdb=>"", :freebase=>"", :originalTitle => 'casablanca', :season=> '1', :episode => '3'}
keepers = [:title, :media, :localeLanguage]

entry.slice(*keepers)
# => {:title=>"casablanca", :media=>"dvd", :localeLanguage=>"en"}

Shorter version (with same result):

entry.slice(*%i(title media localeLanguage))

Use slice! to modify your hash in-place.

like image 112
Benjamin Crouzier Avatar answered Sep 19 '22 14:09

Benjamin Crouzier


I'd use keep_if (requires 1.9.2).

keepers = [:title, :media, :localeLanguage]

entry.keep_if {|k,_| keepers.include? k }

#=> {:title=>"casablanca", :media=>"dvd", :localeLanguage=>"en"}      
like image 27
Mark Thomas Avatar answered Sep 20 '22 14:09

Mark Thomas