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
}
]
I want to get only the id
and start
values.
I've tried:
return_keys = ['id','start']
return_array = events.select{|key,val| key.to_s.in? return_keys}
but this returns an empty array.
If you happen to be using Rails (or don't mind pulling in all or part of ActiveSupport) then you could use
Hash#slice
:Hash#slice
does some extra work under the covers but it is probably fast enough that you won't notice it for small hashes and the clarity is quite nice.Considering that efficiency appears to be a concern, I would suggest the following.
Code
This uses Hash#select, which, unlike Enumerable#select, returns a hash. I've converted
keeper_keys
to a set for fast lookups.Examples
This should do what you want:
Potentially faster (but somewhat less pretty) solution:
If you need
return_keys
to be dynamic: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):
A better solution is to use a hash as your index instead of doing a linear array lookup for each key:
I've adjusted this to use symbols as the key names to match your definition of
events
.This can be further improved by using the
return_keys
as a direct driver:The result is the same. If the subset you're extracting tends to be much smaller than the original, this might be the best approach.