如何在ruby中通过数组为散列创建一个切片,如下所示:
info = { :key1 => "Lorem", :key2 => "something...", :key3 => "Ipsum" }
needed_keys = [:key1, :key3]
info = info.slice( needed_keys )
我想收到:
{ :key1 => "Lorem", :key3 => "Ipsum" }
最佳答案
ActiveSupport的Hash#slice
不接受键数组作为参数,您必须将要提取的键作为单个参数传递,例如通过splatting您的needed_keys
数组:
info.slice(:key1, :key3)
# => {:key1=>"Lorem", :key3=>"Ipsum"}
info.slice(*needed_keys)
# => {:key1=>"Lorem", :key3=>"Ipsum"}
关于ruby - ruby 切片与数组条件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21119074/