Remove keys in hash not in array

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.


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"}      

Tags:

Ruby

Hash