Everyone,

I don't know if you guys are aware of the Ruby/Extensions API. It's a
collection of extensions for Core classes in Ruby. I thought it might
lend itself to the grouping issue we've been having.

In that set of extensions I found an awesome Enumerable method called
'partition_by' which is perfect for taking an array of objects and
dividing them up based on a common attribute (say date). Tom solved it
with his group method, but you might just want to install the extensions
gem and use this method.

Here is the source for said method:
##
def partition_by
  result = {}
  self.each do |e|
    value = yield e
    (result[value] ||= []) << e
  end
  result
 end
##

It's pretty exactly what Tom wrote, irregardless, there are tons of
useful methods in the collection. You can install them like so: `gem
install -r extensions` and you can find the documentation here:
http://extensions.rubyforge.org/rdoc/index.html.

Enjoy!

-Jordan

On 11/22/2006, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:

>Tom,
>
>I wouldn't recommend extending the class Array with a method that
>returns a Hash. A better option would be to extend the Enumerable class
>for this. An example is the 'sort_by' method of the Enumerable class
>which can deal with any type of enumerable (might want to think about
>that as well) and spits out a sorted n-dimensional array. Yours could
>deal with any type of enumerable and spit out a grouped hash.
>
>-Jordan
>
>On 11/22/2006, "Tom Werner" <[EMAIL PROTECTED]> wrote:
>
>>Here's a little group method I just wrote on the Array class (and how to
>>use it) that might serve your purpose well:
>>
>>class Array
>>    def group
>>    groups = {}
>>    self.each do |e|
>>      key = yield e
>>      groups[key] ||= []
>>      groups[key] << e
>>    end
>>    groups
>>    end
>>end
>>
>>class Foo
>>  attr_accessor :year, :title
>>
>>  def initialize(year, title)
>>    self.year = year
>>    self.title = title
>>  end
>>end
>>
>>a = []
>>a << Foo.new(2006, 'Alpha')
>>a << Foo.new(2006, 'Beta')
>>a << Foo.new(2007, 'Gamma')
>>a << Foo.new(2008, 'Delta')
>>
>>ag = a.group { |e| e.year }
>>
>>ag.keys.sort.each do |year|
>>  puts year
>>  ag[year].each do |foo|
>>    puts '  ' + foo.title
>>  end
>>end
>>
>>__END__
>>
>>2006
>>  Alpha
>>  Beta
>>2007
>>  Gamma
>>2008
>>  Delta
>>_______________________________________________
>>Sdruby mailing list
>>[email protected]
>>http://lists.sdruby.com/mailman/listinfo/sdruby
>_______________________________________________
>Sdruby mailing list
>[email protected]
>http://lists.sdruby.com/mailman/listinfo/sdruby
_______________________________________________
Sdruby mailing list
[email protected]
http://lists.sdruby.com/mailman/listinfo/sdruby

Reply via email to