Example Enumerable s group by

July 16th, 2011

This is an example of Ruby's Enumerable class method group_by:

  1 %h2 Accounts
  2 -collection.group_by(&:type).each do |type, accounts|
  3   %h4=type
  4   -accounts.each do |a|
  5     %p=link_to, self.send("#{a.type.underscore}_path",a)
  7 =link_to "New", new_resource_path

Enumerable is truly an awesome class, actually - its a module! Which really exudes Ruby's prowess as a sweet gem of a programming language.

So what does group_by do? It converts an array of hashes (think ActiveRecord arrays) to an array of arrays containing hashes, sorted by one of the keys of the original hashes. This is often useful for sorting a collection of events by day, or in the above example, a collection of accounts by their type.

Do you have a cool example of enumerable's group_by function you'd like to share? I'd love to hear about it!

Yearly Indexes: 2003 2004 2006 2007 2008 2009 2010 2011 2012 2013 2015 2019 2020 2022