Reputation: 809
How can I create an slice for a hash in ruby looking by an array, like this:
info = { :key1 => "Lorem", :key2 => "something...", :key3 => "Ipsum" }
needed_keys = [:key1, :key3]
info = info.slice( needed_keys )
I want to receive:
{ :key1 => "Lorem", :key3 => "Ipsum" }
Upvotes: 3
Views: 2115
Reputation: 19228
ActiveSupport's Hash#slice
doesn't take an array of keys as argument, you have to pass the keys you want to extract as single arguments, for example by splatting your needed_keys
array:
info.slice(:key1, :key3)
# => {:key1=>"Lorem", :key3=>"Ipsum"}
info.slice(*needed_keys)
# => {:key1=>"Lorem", :key3=>"Ipsum"}
Upvotes: 6