Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" }
like image 725
Jorman Bustos Avatar asked Sep 22 '26 19:09

Jorman Bustos


1 Answers

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"}
like image 199
toro2k Avatar answered Sep 24 '26 07:09

toro2k