Begin main content

Functional map_each method for Ruby Hash

I prefer to use functional style programming wherever possible. In many popular dynamic languages such as Perl, Python or Ruby there is quite good support for functional programming with arrays such as Perl and Ruby's map and Python's even better list comprehensions.

With hashes (or dictionaries or whatever you call them) you're usually stuck to sequential programming. Since in Ruby hashes are objects we can inject a nice map_each method into the Hash class which will process each key value pair and the resultant list will have one result for each pair.

class Hash
  def map_each
    ret = []
    self.each do |key, val|
      ret.push yield(key, val)
    end
    ret
  end
end

02:53 PM, 09 May 2009 by Mark Aufflick Permalink | Short Link

Add comment