How can I filter an array of hashes to get only the keys in another array?

This should do what you want:

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

If you need return_keys to be dynamic:

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

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)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)