如何为数组中的ruby创建一个切片,如下所示:
info = { :key1 => "Lorem", :key2 => "something...", :key3 => "Ipsum" }
needed_keys = [:key1, :key3]
info = info.slice( needed_keys )
我想收到:
{ :key1 => "Lorem", :key3 => "Ipsum" }
答案 0 :(得分:4)
ActiveSupport的Hash#slice
不会将一组键作为参数,您必须将要提取的键作为单个参数传递,例如通过splatting needed_keys
数组:
info.slice(:key1, :key3)
# => {:key1=>"Lorem", :key3=>"Ipsum"}
info.slice(*needed_keys)
# => {:key1=>"Lorem", :key3=>"Ipsum"}
答案 1 :(得分:2)
info.select{|k,_| needed_keys.include? k }
答案 2 :(得分:1)
您需要展开数组:
info.slice(*needed_keys)