diff options
author | Marcel Molina <marcel@vernix.org> | 2006-03-01 20:32:10 +0000 |
---|---|---|
committer | Marcel Molina <marcel@vernix.org> | 2006-03-01 20:32:10 +0000 |
commit | 1fdf578c17b38fc5391996d2016f4170bc3bf5ba (patch) | |
tree | 6063dbbf0043d0f187d6655c0ccbade2b1fc4ca4 /activesupport/lib | |
parent | 8368b5960b5128deed17fcf9d7cda5c70da9d972 (diff) | |
download | rails-1fdf578c17b38fc5391996d2016f4170bc3bf5ba.tar.gz rails-1fdf578c17b38fc5391996d2016f4170bc3bf5ba.tar.bz2 rails-1fdf578c17b38fc5391996d2016f4170bc3bf5ba.zip |
Add Enumerable#group_by and Array#in_groups_of
git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@3726 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
Diffstat (limited to 'activesupport/lib')
-rw-r--r-- | activesupport/lib/active_support/core_ext/array.rb | 16 | ||||
-rw-r--r-- | activesupport/lib/active_support/core_ext/enumerable.rb | 29 |
2 files changed, 44 insertions, 1 deletions
diff --git a/activesupport/lib/active_support/core_ext/array.rb b/activesupport/lib/active_support/core_ext/array.rb index ddf2a369c1..897d73866c 100644 --- a/activesupport/lib/active_support/core_ext/array.rb +++ b/activesupport/lib/active_support/core_ext/array.rb @@ -2,4 +2,20 @@ require File.dirname(__FILE__) + '/array/conversions' class Array #:nodoc: include ActiveSupport::CoreExtensions::Array::Conversions + + # Iterate over an array in groups of a certain size, padding any remaining + # slots with specified value (<tt>nil</tt> by default). + # + # E.g. + # + # %w(1 2 3 4 5 6 7).in_groups_of(3) {|g| p g} + # ["1", "2", "3"] + # ["4", "5", "6"] + # ["7", nil, nil] + def in_groups_of(number, fill_with = nil, &block) + require 'enumerator' + collection = dup + collection << fill_with until collection.size.modulo(number).zero? + collection.each_slice(number, &block) + end end diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb index 49e1b7bb90..8a097dcd90 100644 --- a/activesupport/lib/active_support/core_ext/enumerable.rb +++ b/activesupport/lib/active_support/core_ext/enumerable.rb @@ -6,4 +6,31 @@ module Enumerable #:nodoc: end match end -end
\ No newline at end of file + + # Collect an enumerable into sets, grouped by the result of a block. Useful, + # for example, for grouping records by date. + # + # e.g. + # + # latest_transcripts.group_by(&:day).each do |day, transcripts| + # p "#{day} -> #{transcripts.map(&:class) * ', '}" + # 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" + def group_by + inject([]) do |groups, element| + value = yield(element) + if (last_group = groups.last) && last_group.first == value + last_group.last << element + else + groups << [value, [element]] + end + groups + end + end +end |