Pete Hodgson

Software Delivery Consultant

Ruby Facets: the mash method

February 18, 2010

I keep meaning to write up some of the useful gems (if you'll pardon the pun) which are hidden in the super-handy Facets gem. Today I'll cover Enumerable#mash.

Let's say you have a list of Users, and you'd like to create a hash which lets you look up the Users based on their login. You might write something like:

def create_login_hash_for( users )
  user_login_hash = {}
  users.each do |user|
    user_login_hash[user.login] = user

With Enumerable#mash, you can trim that down to:

def create_login_hash_for( users )
  users.mash do |user|

This is much more succinct. More importantly, it expresses the intention more clearly.