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.
This should do what you want:
Potentially faster (but somewhat less pretty) solution:
If you need
return_keysto be dynamic:Note that, in your code,
selectpicks 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):