Group elements by category

Hi! I’m a newbie on RoR, i’m just starting with it but i like it! But
I don’t know how to do this avoiding loops,etc…

I have a collection of Link instances; this model has a “Category”
attribute. I need to group them on the controller in order to show
them separated on the view. How can I do this nicely?

Any suggestion?

Thanks so much!

Sergi.

I have a collection of Link instances; this model has a “Category”
attribute. I need to group them on the controller in order to show
them separated on the view. How can I do this nicely?

foo = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
groups = Hash.new{|h, k| h[k] = []}
foo.each{|i| groups[i] << i}

On Fri, Jan 28, 2011 at 2:44 PM, Anurag P.
[email protected]wrote:

foo = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
groups = Hash.new{|h, k| h[k] = []}
foo.each{|i| groups[i] << i}

groups => {1=>[1], 2=>[2, 2], 3=>[3, 3, 3], 4=>[4, 4, 4, 4]}
groups[3] => [3, 3, 3]

I think Rails provides this method for pre-1.8.7, but for 1.8.7 and
higher
you can use group_by:

(1…10).group_by { |n| n % 2 }
=> {0=>[2, 4, 6, 8, 10], 1=>[1, 3, 5, 7, 9]}

which is more easily generalised than the quoted code’s approach, and
easier
to read, certainly. As an exercise, maybe try implementing your own
Enumerable#group_by method; it’s good for getting your head around how
#each
and mixins work, as well as yielding to blocks.

On Jan 28, 4:43pm, Adam P. [email protected] wrote:

and mixins work, as well as yielding to blocks.
Many thanks!

what i finally did :

%w(category_1 category_2 category_3).map{|c| ls.select{|li|
li.category == c}}

where ls are all the elements i need to group… anyway, the native
rails group_by method is much better, i didnt know it exists!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs