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