# For Loop

**URL:** <https://www.ruby-forum.com/t/for-loop/109022>\
**Category:** Rails\
**Created:** [July 10, 2007, 6:39pm UTC](https://www.ruby-forum.com/t/for-loop/109022 "2007-07-10T18:39:14Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![pete](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/3ab097/32.png) [@pete](https://www.ruby-forum.com/u/pete)\
**Post date:** [July 10, 2007, 6:39pm UTC](https://www.ruby-forum.com/t/for-loop/109022/1 "2007-07-10T18:39:14Z")

</div>

Hi there,

I’m working on my first real rails application (meaning not one out of  
a book), and I’m not quite sure how to display the results of a  
grouped query. This is what I have in my controller:

@s = Story.find\_recent\_public\_stories  
@stories = @s.group\_by {|story| story.section}

In my for loop, I’ve tried various combinations of things like  
@stories.section.name, but so far, I haven’t had any luck.  
@stories.to\_xml and @stories.to\_yaml works fine, though. Everything  
else returns a NoMethodError.

My ultimate goal is to get a list of stories sorted by category.

Thanks!

---

<div class="post-metadata">

**Author:** ![pete](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/3ab097/32.png) [@pete](https://www.ruby-forum.com/u/pete)\
**Post date:** [July 10, 2007, 8:00pm UTC](https://www.ruby-forum.com/t/for-loop/109022/2 "2007-07-10T20:00:45Z")

</div>

Hi Pete,

In your case group\_by returns a hash where the keys are sections and  
the values are arrays of stories, so you need to do something like  
this:

in your controller:  
@s = Story.find\_recent\_public\_stories  
@story\_lookup = @s.group\_by{ |story| story.section }

in your view:  
\<% @story\_lookup.each do |section, stories| %\>

## \<%= section.name %\>
 \<% for story in stories %\> ... do something with story ... \<% end %\> \<% end %\>

Ryan B. has a Railcast on group\_by: \<[Ruby on Rails Screencasts - RailsCasts](http://railscasts.com/episodes/)  
29\>

-Brad.
