2

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" }
mu is too short
  • 426,620
  • 70
  • 833
  • 800
Jorman Bustos
  • 799
  • 2
  • 6
  • 12

3 Answers3

5

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"}
Community
  • 1
  • 1
toro2k
  • 19,020
  • 7
  • 64
  • 71
2
info.select{|k,_| needed_keys.include? k }
Santhosh
  • 28,097
  • 9
  • 82
  • 87
1

You need to expand array:

info.slice(*needed_keys)
BroiSatse
  • 44,031
  • 8
  • 61
  • 86