如何过滤哈希数组以仅获取另一个数组中的密钥? [英] How can I filter an array of hashes to get only the keys in another array?
问题描述
我正在尝试获取数组中每个哈希的键的子集.
I'm trying get a subset of keys for each hash in an array.
散列实际上更大,但我认为这更容易理解:
The hashes are actually much larger, but I figured this is easier to understand:
[
{
id:2,
start: "3:30",
break: 30,
num_attendees: 14
},
{
id: 3,
start: "3: 40",
break: 40,
num_attendees: 4
},
{
id: 4,
start: "4: 40",
break: 10,
num_attendees: 40
}
]
我只想获取id
和start
值.
我尝试过:
return_keys = ['id','start']
return_array = events.select{|key,val| key.to_s.in? return_keys}
但是这将返回一个空数组.
but this returns an empty array.
推荐答案
这应该做您想要的:
events.map do |hash|
hash.select do |key, value|
[:id, :start].include? key
end
end
可能更快(但不太漂亮)的解决方案:
Potentially faster (but somewhat less pretty) solution:
events.map do |hash|
{ id: hash[:id], start: hash[:start] }
end
如果您需要return_keys
是动态的:
return_keys = [:id, :start]
events.map do |hash|
{}.tap do |new_hash|
return_keys.each do |key|
new_hash[key] = hash[key]
end
end
end
请注意,在您的代码中,select
从 array 中挑选元素,因为这就是您所调用的内容,但不会更改数组中包含的哈希.
Note that, in your code, select
picks out elements from the array, since that's what you called it on, but doesn't change the hashes contained within the array.
如果您担心性能,我已经对此处列出的所有解决方案进行了基准测试(代码 ):
If you're concerned about performance, I've benchmarked all of the solutions listed here (code):
user system total real
amarshall 1 0.140000 0.000000 0.140000 ( 0.140316)
amarshall 2 0.060000 0.000000 0.060000 ( 0.066409)
amarshall 3 0.100000 0.000000 0.100000 ( 0.101469)
tadman 1 0.140000 0.010000 0.150000 ( 0.145489)
tadman 2 0.110000 0.000000 0.110000 ( 0.111838)
mu 0.130000 0.000000 0.130000 ( 0.128688)
这篇关于如何过滤哈希数组以仅获取另一个数组中的密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!