# RCR: Array#to\_h

**URL:** <https://rubytalk.org/t/rcr-array-to-h/21858>\
**Category:** ruby-talk\
**Created:** [25 October 2005 06:27 UTC](https://rubytalk.org/t/rcr-array-to-h/21858 "2005-10-25T06:27:30Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Daniel\_Sheppard](https://avatars.discourse-cdn.com/v4/letter/d/db5fbb/32.png) [@Daniel\_Sheppard](https://rubytalk.org/u/Daniel_Sheppard)\
**Post date:** [25 October 2005 06:27 UTC](https://rubytalk.org/t/rcr-array-to-h/21858/1 "2005-10-25T06:27:30Z")

</div>

Maybe what we're actually after here is the equivalent to map/collect  
that produces a hash instead. I really don't like the name "hash\_map",  
but it was either that or "hashify". If you want the index behaviour,  
you can do that with an Enumerable.

module Enumerable  
&nbsp;&nbsp;def hash\_map  
&nbsp;&nbsp;&nbsp;&nbsp;h = {}  
&nbsp;&nbsp;&nbsp;&nbsp;each do |x|  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;k,\*v = yield(\*x)  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;h[k] = \*v  
&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;&nbsp;&nbsp;h  
&nbsp;&nbsp;end  
end  
class Hash  
&nbsp;&nbsp;def hash\_map!(&block)  
&nbsp;&nbsp;&nbsp;&nbsp;replace(hash\_map(&block))  
&nbsp;&nbsp;end  
end

#now we can create a hash with all the values double that of a previous  
hash:

hash = {'a'=\>1, 'b'=\> 2}  
hash2 = hash.hash\_map { |k,v| [k,(v\*2)]}

#=\> {"a"=\>2, "b"=\>4}

#or form a hash from an array:

arr = [1,2,3,4,5,6]  
hash3 = arr.hash\_map { |x| [x, x \* 5] }

#=\>{5=\>25, 6=\>30, 1=\>5, 2=\>10, 3=\>15, 4=\>20}

The main problem with the above is the fact that the block needs to  
return two values, and it's quite awkward to do that.

> **···**
>
> > -----Original Message-----  
> > From: nobuyoshi nakada [mailto:nobuyoshi.nakada@ge.com]  
> > Sent: Tuesday, 25 October 2005 3:39 PM  
> > To: ruby-talk ML  
> > Subject: Re: RCR: Array#to\_h
> > 
> > Hi,
> > 
> > At Tue, 25 Oct 2005 13:37:01 +0900,  
> > Trans wrote in [ruby-talk:162411]:  
> > \> I think the proposal is over specialized. Why should the array  
> > \> elements neccessarily become keys?
> > 
> > Yes, agreed, and I doubt that there is a solution which  
> > satisfy everyone for this issue.
> > 
> > --  
> > Nobu Nakada
> 
> #####################################################################################  
> This email has been scanned by MailMarshal, an email content filter.  
> #####################################################################################
