# Building a hash from query results

**URL:** <https://www.ruby-forum.com/t/building-a-hash-from-query-results/118429>\
**Category:** Rails\
**Created:** [October 26, 2007, 9:09pm UTC](https://www.ruby-forum.com/t/building-a-hash-from-query-results/118429 "2007-10-26T21:09:27Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jcernelli](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/73ab20/32.png) [@jcernelli](https://www.ruby-forum.com/u/jcernelli)\
**Post date:** [October 26, 2007, 9:09pm UTC](https://www.ruby-forum.com/t/building-a-hash-from-query-results/118429/1 "2007-10-26T21:09:27Z")

</div>

I need to build a hash out of the results of a query.

I had something like this in mind:

questions = survey\_questions.find( params[:yaddayadda])  
myHash = hash.new

for questions.each do |question|  
foo = question.some\_field1  
bar = question.some\_field2  
myHash[foo] = bar  
end

I’m guessing there is a BetterWay™. Any ideas?

---

<div class="post-metadata">

**Author:** ![jcernelli](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/73ab20/32.png) [@jcernelli](https://www.ruby-forum.com/u/jcernelli)\
**Post date:** [October 26, 2007, 9:18pm UTC](https://www.ruby-forum.com/t/building-a-hash-from-query-results/118429/2 "2007-10-26T21:18:48Z")

</div>

On 10/26/07, Joe C. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> myHash[foo] = bar  
> end
> 
> I’m guessing there is a BetterWay™. Any ideas?

Use inject

@questions.inject({}) do |memo, question|  
memo.update question.some\_field1 =\> question.some\_field2  
end

–  
Rick O.  
[http://lighthouseapp.com](http://lighthouseapp.com)  
[http://weblog.techno-weenie.net](http://weblog.techno-weenie.net)  
[http://mephistoblog.com](http://mephistoblog.com)

---

<div class="post-metadata">

**Author:** ![jcernelli](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/73ab20/32.png) [@jcernelli](https://www.ruby-forum.com/u/jcernelli)\
**Post date:** [October 30, 2007, 11:44pm UTC](https://www.ruby-forum.com/t/building-a-hash-from-query-results/118429/3 "2007-10-30T23:44:20Z")

</div>

Wow, really nice trick, thanks a lot, that will really help. I’m trying  
the  
implementation now, thanks much!
