group_by
- 1.0.0
- 1.1.6
- 1.2.6 (0)
- 2.0.3 (0)
- 2.1.0 (1)
- 2.2.1 (0)
- 2.3.8 (0)
- 3.0.0 (0)
- 3.0.9 (-2)
- 3.1.0 (0)
- 3.2.1 (0)
- 3.2.8 (0)
- 3.2.13 (0)
- 4.0.2
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3
- 6.0.0
- 6.1.3.1
- 6.1.7.7
- 7.0.0
- 7.1.3.2
- 7.1.3.4
- What's this?
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"
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]}
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.