Jorman Bustos
Jorman Bustos

Reputation: 809

ruby slice with array cirteria

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

Answers (3)

toro2k
toro2k

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

BroiSatse
BroiSatse

Reputation: 44675

You need to expand array:

info.slice(*needed_keys)

Upvotes: 1

Santhosh
Santhosh

Reputation: 29124

info.select{|k,_| needed_keys.include? k }

Upvotes: 2

Related Questions