Arrays 从其键属于数组的哈希中选择键值对

Arrays 从其键属于数组的哈希中选择键值对,arrays,ruby,hash,Arrays,Ruby,Hash,我有一组钥匙: keys = ["first_name", "last_name", "foo"] 和散列: hsh = {"first_name" => "tester", "zoo" => "loo", "foo" => "bar"} 我想提取其键在数组中的键值对,以获得: res = {"first_name" => "tester", "foo" => "bar"} 有办法吗?试试这个: hsh.select{ |k, v| keys.include?

我有一组钥匙:

keys = ["first_name", "last_name", "foo"]
和散列:

hsh = {"first_name" => "tester", "zoo" => "loo", "foo" => "bar"}
我想提取其键在数组中的键值对,以获得:

res = {"first_name" => "tester", "foo" => "bar"}
有办法吗?

试试这个:

hsh.select{ |k, v| keys.include?(k) } 
这是一种方法:

hsh.select { |k,_| k.in?(keys) }
# => {"first_name" => "tester", "foo" => "bar"}

请注意,尽管这比使用
包含?
要短,但这取决于Rails是否存在。

您可以使用
拒绝

hsh.slice *keys
# => {"first_name" => "tester", "foo" => "bar"}
hsh.reject { |k| !keys.include? k } #=> {"first_name"=>"tester", "foo"=>"bar"}
hsh.keep_if { |key| keys.include? key }

如果而不是
选择
,则调用
keep\u感觉更自然:

hsh.reject { |k| !keys.include? k } #=> {"first_name"=>"tester", "foo"=>"bar"}
hsh.keep_if { |key| keys.include? key }

另外,
keep_,如果
从散列中删除了不需要的对。

检查答案您可以在答案中尝试类似切片的方法。@。我们正在寻找不同或更多的ruby方法来实现这一点这是ruby>=2.5.0(Rails之前有这个核心扩展)的方式,不需要
。选择{}
。拒绝{}
。如果{}
继续保留。请参见仅计数时的字符数。