带有数组标准的ruby切片

时间:2014-01-14 16:48:27

标签: ruby ruby-on-rails-3 hash ruby-on-rails-4

如何为数组中的ruby创建一个切片,如下所示:

info         = { :key1 => "Lorem", :key2 => "something...", :key3 => "Ipsum" }
needed_keys  = [:key1, :key3]
info         = info.slice( needed_keys )

我想收到:

{ :key1 => "Lorem", :key3 => "Ipsum" }

3 个答案:

答案 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)