method

group_by

Importance_3
v3.2.13 - Show latest stable - 2 notes - Class: Enumerable
group_by() public

Collect an enumerable into sets, grouped by the result of a block. Useful, for example, for grouping records by date.

Example:

latest_transcripts.group_by(&:day).each do |day, transcripts|
  p "#{day} -> #{transcripts.map(&:class).join(', ')}"
end
"2006-03-01 -> Transcript"
"2006-02-28 -> Transcript"
"2006-02-27 -> Transcript, Transcript"
"2006-02-26 -> Transcript, Transcript"
"2006-02-25 -> Transcript"
"2006-02-24 -> Transcript, Transcript"
"2006-02-23 -> Transcript"
Show source
Register or log in to add new notes.
April 6, 2009
6 thanks

Array clustering

Sometimes you don’t want to mangle sequence of an array and just want to group adjacent values. Here’s a nice method to do so (drop it in your initializers directory or something):

module Enumerable
  # clumps adjacent elements together
  # >> [2,2,2,3,3,4,2,2,1].cluster{|x| x}
  # => [[2, 2, 2], [3, 3], [4], [2, 2], [1]]
  def cluster
    cluster = []
    each do |element|
      if cluster.last && yield(cluster.last.last) == yield(element)
        cluster.last << element
      else
        cluster << [element]
      end
    end
    cluster
  end
end

Similarly you can do the clustering on more complex items. For instance you want to cluster Documents on creation date and their type:

Document.all.cluster{|document| [document.created_on, document.type]}
January 26, 2010
2 thanks

returns an ActiveSupport::OrderedHash

Returns an ActiveSupport::OrderedHash, which is a subclass of Hash that preserves order. If you’re running Ruby 1.9, it is simply an alias for Hash. Surprisingly, you might not realize that OrderedHash is preserving order since it delegates its inspect method to Hash. More at ActiveSupport::OrderedHash.