Michiel de Mare

The Daily Method - maph

Mapping Over An Array Of Hashes

Enumerable#maph is a trivial method (really trivial, in Ruby 3 syntax its definition is def maph(k) = map { _1[k] }) that nevertheless makes working with arrays of hashes a bit nicer. Why define a block when you don't have to?

Usage:

pks.sort_by { |f| f["pk"] }.map { |f| f["name"] }

turns into:

pks.sort_by { |f| f["pk"] }.maph("name")

maph works with Symbols and Strings, and for that matter on anything that responds to the index operator.

To add support for other Enumerable methods than map we can add a method to Enumerator. I'll name the method key.

class Enumerator
  def key(k) = each { _1[k] }
end

Then we can turn our previous example into pks.sort_by.key("pk").map.key("name")