h

Being Agile

Pete Hodgson's blurgh

Ruby Facets: The Mash Method

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
  end
  user_login_hash
end

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

def create_login_hash_for( users )
  users.mash do |user|
    [user.login,user]
  end
end

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