# Group By Hash Problem. Help!

**URL:** <https://www.ruby-forum.com/t/group-by-hash-problem-help/148068>\
**Category:** Rails\
**Created:** [September 8, 2008, 10:32pm UTC](https://www.ruby-forum.com/t/group-by-hash-problem-help/148068 "2008-09-08T22:32:17Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![blink](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/b38774/32.png) [@blink](https://www.ruby-forum.com/u/blink)\
**Post date:** [September 8, 2008, 10:32pm UTC](https://www.ruby-forum.com/t/group-by-hash-problem-help/148068/1 "2008-09-08T22:32:17Z")

</div>

I have a current\_user via resthul\_auth thast HABTM projects. In my  
projects\_controller’s index action, I have

def index  
@page\_title = “All Projects”  
if current\_user.admin?  
@projects = current\_account.projects  
else  
@projects = current\_user.projects  
end

```
@project_companies = @projects.group_by(&:primary_company)

```

The problem is, the HASH can’t be sorted - in my view, I group the  
projects by their primary company. The group\_by gives me a hash with a  
primary company object as the key. I can either use the  
:primary\_company\_id, which just gives me the integer, or the  
:primary\_company, which through some magic gives me a whole object as a  
hash key. Is there any inbetween? something like:

@project\_companies = @projects.group\_by(&:primary\_company.name) (which  
didn’t work)

that will only give me the name string from that object as a hash key?  
Otherwise the view isn’t in alphabetical order, or in any order really.  
I’m kind of stuck!!!

---

<div class="post-metadata">

**Author:** ![blink](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/b38774/32.png) [@blink](https://www.ruby-forum.com/u/blink)\
**Post date:** [September 9, 2008, 3:45am UTC](https://www.ruby-forum.com/t/group-by-hash-problem-help/148068/2 "2008-09-09T03:45:24Z")

</div>

On 8 Sep 2008, at 21:32, Jarrett G. wrote:

> ```
> @projects = current_user.projects
> 
> ```
> 
> :primary\_company, which through some magic gives me a whole object  
> as a  
> hash key. Is there any inbetween? something like:
> 
> @project\_companies = @projects.group\_by(&:primary\_company.name) (which  
> didn’t work)

You need to undestant that &:primary\_company is just shorthand which  
is (basically even though that’s not quite how it’s implemented)  
equivalent to

@project\_companies = @projects.group\_by {|project|  
project.primary\_company }

and now it’s easy to change that to

@project\_companies = @projects.group\_by {|project|  
project.primary\_company.name }

Fred
