Group elements by category

P

poles_apart

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.
 
A

Anurag Priyam

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}
groups => {1=>[1], 2=>[2, 2], 3=>[3, 3, 3], 4=>[4, 4, 4, 4]}
groups[3] => [3, 3, 3]
 
A

Adam Prescott

[Note: parts of this message were removed to make it a legal post.]

foo = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
groups = Hash.new{|h, k| h[k] = []}
foo.each{|i| groups << 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:
=> {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.
 
S

Sergi Villanueva

[Note:  parts of this message were removed to make it a legal post.]

foo = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
groups = Hash.new{|h, k| h[k] = []}
foo.each{|i| groups << 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:

=> {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.


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!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,141
Messages
2,570,813
Members
47,357
Latest member
sitele8746

Latest Threads

Top