Good call on using Hash#values!
On Wed, Mar 26, 2008 at 1:02 PM, Rob Kaufman <[EMAIL PROTECTED]> wrote:
> Group_by is the command your looking for Tommy. Running that on your
> array gets your this:
> autos = [{:id => 1, :name => 'toyota'}, {:id => 2, :name => 'ford' }, {:id
> => 3, :name => 'toyota'} ]
> autos.group_by {|h| h[:name]}
> #=> {"toyota"=>[{:name=>"toyota", :id=>1}, {:name=>"toyota", :id=>3}],
> "ford"=>[{:name=>"ford", :id=>2}]}
>
> you can then call .values on your hash to get the arrays like your looking
> for (similar to Jordan's collect statement, but much faster for large sets)
>
> It is worth noting that group_by is added to Rails, and does not exist in
> core Ruby. It is defined in activesupport in the file
> rails/activesupport/lib/active_support/core_ext/enumerable.rb
>
> its definition (in case your in Rubyland and not Railsville)
> def group_by
> inject({}) do |groups, element|
> (groups[yield(element)] ||= []) << element
> groups
> end
> end
>
>
> Rob
> On Wed, Mar 26, 2008 at 12:31 PM, Jordan Fowler <[EMAIL PROTECTED]>
> wrote:
>
> > autos = [{:id => 1, :name => 'toyota'}, {:id => 2, :name => 'ford' },
> > {:id => 3, :name => 'toyota'} ]
> > autos.group_by {|h| h[:name]}.collect {|k,v| v} #=> [[{:name=>"toyota",
> > :id=>1}, {:name=>"toyota", :id=>3}], [{:name=>"ford", :id=>2}]]
> >
> >
> >
> > On Wed, Mar 26, 2008 at 12:12 PM, tommy <[EMAIL PROTECTED]> wrote:
> >
> > >
> > > hey guys,
> > > got an array question:
> > >
> > > class Autos
> > > with a variable name
> > >
> > > I have an array of Autos. I want to split this array into chunks of
> > > arrays grouped by name.
> > >
> > > ie, Autos = [{id:1, name:toyota}, {id:2, name:ford}, {id:3,
> > > name:toyota} ]
> > > would create two arrays in a super array
> > > [ [{id:1, name:toyota},{id:3, name:toyota}] , [{id:2, name:ford:}] ]
> > >
> > > i have the unique list of names.
> > >
> > > I was roughly thinking of sorting the array by name and finding the
> > > first occurrence of each name and doing a slice.
> > >
> > > Is there a faster approach?
> > >
> > >
> >
> >
> > --
> > Jordan A. Fowler
> > 2621 First Ave Apt 5
> > San Diego, CA 92103
> > E-mail: [EMAIL PROTECTED]
> > Website: http://www.jordanfowler.com
> > Phone: 406.546.8055
> >
> >
> >
>
> >
>
--
Jordan A. Fowler
2621 First Ave Apt 5
San Diego, CA 92103
E-mail: [EMAIL PROTECTED]
Website: http://www.jordanfowler.com
Phone: 406.546.8055
--~--~---------~--~----~------------~-------~--~----~
SD Ruby mailing list
[email protected]
http://groups.google.com/group/sdruby
-~----------~----~----~----~------~----~------~--~---