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?
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With