# About array to hash conversion

**URL:** <https://rubytalk.org/t/about-array-to-hash-conversion/43656>\
**Category:** ruby-talk\
**Created:** [9 January 2008 21:31 UTC](https://rubytalk.org/t/about-array-to-hash-conversion/43656 "2008-01-09T21:31:42Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![Holden\_Holden](https://avatars.discourse-cdn.com/v4/letter/h/6de8d8/32.png) [@Holden\_Holden](https://rubytalk.org/u/Holden_Holden)\
**Post date:** [9 January 2008 21:31 UTC](https://rubytalk.org/t/about-array-to-hash-conversion/43656/1 "2008-01-09T21:31:42Z")

</div>

Hi,

I want to convert an array (with pairs [key,value]) to a hash. After  
googling a bit I got:

1) Hash[\*array.flatten]

But this is not safe as Array#flatten is recursive.

2) array.inject({}) { |m, e| m[e[0]] = e[1]; m }

Too ugly to consider.

3) Hash[\*array.flatten(1)]

That's my own attempt. It only works for Ruby \> 1.9.

But I am still wondering why...

- Array objects have no "to\_h" method?  
- Hasy[\*array] don't accept the [key,value] pairs (as Hash#to\_a calls  
return)?

thanks,  
holden

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Jeremy\_Weiskotten](https://avatars.discourse-cdn.com/v4/letter/j/ed8c4c/32.png) [@Jeremy\_Weiskotten](https://rubytalk.org/u/Jeremy_Weiskotten)\
**Post date:** [9 January 2008 23:59 UTC](https://rubytalk.org/t/about-array-to-hash-conversion/43656/2 "2008-01-09T23:59:32Z")

</div>

You could open up the Array class and add a to\_hash method that uses the  
ugly inject idiom to make it more convenient.

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![yermej](https://avatars.discourse-cdn.com/v4/letter/y/b2d939/32.png) [@yermej](https://rubytalk.org/u/yermej)\
**Post date:** [10 January 2008 00:04 UTC](https://rubytalk.org/t/about-array-to-hash-conversion/43656/3 "2008-01-10T00:04:57Z")

</div>

These would only work in one specific case. What would this do?

[1, 2, 3].to\_h

> **···**
>
> On Jan 9, 3:31 pm, Holden Holden \<pyar...@gmail.com\> wrote:
> 
> > Hi,
> > 
> > I want to convert an array (with pairs [key,value]) to a hash. After  
> > googling a bit I got:
> > 
> > 1) Hash[\*array.flatten]
> > 
> > But this is not safe as Array#flatten is recursive.
> > 
> > 2) array.inject({}) { |m, e| m[e[0]] = e[1]; m }
> > 
> > Too ugly to consider.
> > 
> > 3) Hash[\*array.flatten(1)]
> > 
> > That's my own attempt. It only works for Ruby \> 1.9.
> > 
> > But I am still wondering why...
> > 
> > - Array objects have no "to\_h" method?  
> > - Hasy[\*array] don't accept the [key,value] pairs (as Hash#to\_a calls  
> > return)?

---

<div class="post-metadata">

**Author:** ![Wally\_T\_Terrible](https://avatars.discourse-cdn.com/v4/letter/w/eb8c5e/32.png) [@Wally\_T\_Terrible](https://rubytalk.org/u/Wally_T_Terrible)\
**Post date:** [10 January 2008 00:10 UTC](https://rubytalk.org/t/about-array-to-hash-conversion/43656/4 "2008-01-10T00:10:25Z")

</div>

I just did this myself. Because I knew how the data was stored in the array, I was able to control how I put it into the hash. What I did was this:  
&nbsp;&nbsp;&nbsp;&nbsp;myArray=['255','10','258','08','154','34'] #(etc)  
&nbsp;&nbsp;&nbsp;&nbsp;myHash={}  
&nbsp;&nbsp;&nbsp;&nbsp;c=0  
&nbsp;&nbsp;&nbsp;&nbsp;while c\<=myArray.size  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;myHash.store(myArray[c],myArray[c+1])  
&nbsp;&nbsp;&nbsp;&nbsp;c+=2  
&nbsp;&nbsp;&nbsp;&nbsp;end

I don't suggest that this absolutely the best way to do it, and it may not work if you don't know your data structure in the array but it was a quick and easy way for me to solve my problem.

Holden Holden wrote:

> **···**
>
> > Hi,
> > 
> > I want to convert an array (with pairs [key,value]) to a hash. After  
> > googling a bit I got:
> > 
> > 1) Hash[\*array.flatten]
> > 
> > But this is not safe as Array#flatten is recursive.
> > 
> > 2) array.inject({}) { |m, e| m[e[0]] = e[1]; m }
> > 
> > Too ugly to consider.
> > 
> > 3) Hash[\*array.flatten(1)]
> > 
> > That's my own attempt. It only works for Ruby \> 1.9.
> > 
> > But I am still wondering why...
> > 
> > - Array objects have no "to\_h" method?  
> > - Hasy[\*array] don't accept the [key,value] pairs (as Hash#to\_a calls  
> > return)?
> > 
> > thanks,  
> > holden

---

<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:** [10 January 2008 05:18 UTC](https://rubytalk.org/t/about-array-to-hash-conversion/43656/5 "2008-01-10T05:18:43Z")

</div>

> I want to convert an array (with pairs [key,value]) to a hash. After  
> googling a bit I got:
> 
> 1) Hash[\*array.flatten]
> 
> But this is not safe as Array#flatten is recursive.
> 
> 2) array.inject({}) { |m, e| m[e[0]] = e[1]; m }
> 
> Too ugly to consider.

array.inject({}) {|h,(k,v)| h[k]=v; h}

is still ugly, but perhaps you may consider it.

Also, arrays of arrays can be used directly in a hash-like manner:

array = [[1,2],[3,4]]  
array.assoc(3)  
=\> [3,4]

which may be useful, depending on what you're doing (it won't have hash  
performance, but it may do)

Dan.

---

<div class="post-metadata">

**Author:** ![Robert\_K1](https://yyz1.discourse-cdn.com/flex029/user_avatar/rubytalk.org/robert_k1/32/1830_2.png) [@Robert\_K1](https://rubytalk.org/u/Robert_K1)\
**Post date:** [10 January 2008 08:12 UTC](https://rubytalk.org/t/about-array-to-hash-conversion/43656/6 "2008-01-10T08:12:37Z")

</div>

You can do this:

array.inject({}) {|ha, (k, v)| ha[k] = v; ha}

Is this nicer according to your standards?

Kind regards

robert

> **···**
>
> 2008/1/9, Holden Holden \<pyarnau@gmail.com\>:
> 
> > I want to convert an array (with pairs [key,value]) to a hash. After  
> > googling a bit I got:
> > 
> > 1) Hash[\*array.flatten]
> > 
> > But this is not safe as Array#flatten is recursive.
> > 
> > 2) array.inject({}) { |m, e| m[e[0]] = e[1]; m }
> > 
> > Too ugly to consider.
> 
> --  
> use.inject do |as, often| as.you\_can - without end

---

<div class="post-metadata">

**Author:** ![Jeremy\_Weiskotten](https://avatars.discourse-cdn.com/v4/letter/j/ed8c4c/32.png) [@Jeremy\_Weiskotten](https://rubytalk.org/u/Jeremy_Weiskotten)\
**Post date:** [10 January 2008 00:00 UTC](https://rubytalk.org/t/about-array-to-hash-conversion/43656/7 "2008-01-10T00:00:10Z")

</div>

class Array  
&nbsp;&nbsp;def to\_hash  
&nbsp;&nbsp;&nbsp;&nbsp;inject({}) { |m, e| m[e[0]] = e[1]; m }  
&nbsp;&nbsp;end  
end

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Holden\_Holden](https://avatars.discourse-cdn.com/v4/letter/h/6de8d8/32.png) [@Holden\_Holden](https://rubytalk.org/u/Holden_Holden)\
**Post date:** [10 January 2008 09:34 UTC](https://rubytalk.org/t/about-array-to-hash-conversion/43656/8 "2008-01-10T09:34:58Z")

</div>

yermej wrote:

> **···**
>
> > On Jan 9, 3:31�pm, Holden Holden \<pyar...@gmail.com\> wrote:
> > 
> > > return)?
> > 
> > These would only work in one specific case. What would this do?
> > 
> > [1, 2, 3].to\_h
> 
> That's why I prefer [key, value] pairs, to avoid any ambiguity.
> 
> However, a theorical [1,2,3].to\_h should give the same error than  
> Hash[\*array] gives:
> 
> irb(main):002:0\> Hash[\*[1,2,3]]  
> ArgumentError: odd number of arguments for Hash  
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![Holden\_Holden](https://avatars.discourse-cdn.com/v4/letter/h/6de8d8/32.png) [@Holden\_Holden](https://rubytalk.org/u/Holden_Holden)\
**Post date:** [10 January 2008 09:53 UTC](https://rubytalk.org/t/about-array-to-hash-conversion/43656/9 "2008-01-10T09:53:43Z")

</div>

Robert Klemme wrote:

> You can do this:
> 
> array.inject({}) {|ha, (k, v)| ha[k] = v; ha}
> 
> Is this nicer according to your standards?

Thanks. Yes, it's clearer to separate key/value on the args. I must  
clarify that by "too ugly to consider" I meant "I imagine there is a  
nicer way to do it".

Inject solutions are fine, short and clear, but I am still puzzled why  
Hash[\*array] and Hash#to\_a are not specular (maybe this is a question  
for a ruby-dev forum, though)

regards

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![Robert\_K1](https://yyz1.discourse-cdn.com/flex029/user_avatar/rubytalk.org/robert_k1/32/1830_2.png) [@Robert\_K1](https://rubytalk.org/u/Robert_K1)\
**Post date:** [10 January 2008 09:42 UTC](https://rubytalk.org/t/about-array-to-hash-conversion/43656/10 "2008-01-10T09:42:30Z")

</div>

There is however one issue with a general Array to Hash conversion  
routine: there are different ways to convert a Hash and to me it's not  
clear which one should be the default. Options I can see so far:

1. if array contains pairs use them as key and value for the Hash

2. if array is flat use consecutive entries for key and value (fails  
with odd number of entries)

3. use indexes as keys and entries as values, e.g.

ar.to\_enum(:each\_with\_index).inject({}) {|h, (v,k)| h[k]=v;h}

The last one has not been mentioned so far but there might actually be  
uses for this (i.e. when one wants to replace an Array with a Hash).  
Dunno how often this might occur though.

There are probably other valid default conversion candidates, too.

Kind regards

robert

> **···**
>
> 2008/1/10, Holden Holden \<pyarnau@gmail.com\>:
> 
> > yermej wrote:  
> > \> On Jan 9, 3:31�pm, Holden Holden \<pyar...@gmail.com\> wrote:  
> > \>\>  
> > \>\> return)?  
> > \> These would only work in one specific case. What would this do?  
> > \>  
> > \> [1, 2, 3].to\_h
> > 
> > That's why I prefer [key, value] pairs, to avoid any ambiguity.
> > 
> > However, a theorical [1,2,3].to\_h should give the same error than  
> > Hash[\*array] gives:
> > 
> > irb(main):002:0\> Hash[\*[1,2,3]]  
> > ArgumentError: odd number of arguments for Hash
> 
> --  
> use.inject do |as, often| as.you\_can - without end

---

<div class="post-metadata">

**Author:** ![Stefan\_Rusterholz](https://avatars.discourse-cdn.com/v4/letter/s/e495f1/32.png) [@Stefan\_Rusterholz](https://rubytalk.org/u/Stefan_Rusterholz)\
**Post date:** [10 January 2008 16:54 UTC](https://rubytalk.org/t/about-array-to-hash-conversion/43656/11 "2008-01-10T16:54:08Z")

</div>

Holden Holden wrote:

> yermej wrote:
> 
> > > return)?
> > 
> > These would only work in one specific case. What would this do?
> > 
> > [1, 2, 3].to\_h
> 
> That's why I prefer [key, value] pairs, to avoid any ambiguity.
> 
> However, a theorical [1,2,3].to\_h should give the same error than  
> Hash[\*array] gives:
> 
> irb(main):002:0\> Hash[\*[1,2,3]]  
> ArgumentError: odd number of arguments for Hash

I disagree. Array#to\_hash should work so that hash.to\_a.to\_hash == hash,  
in other words it should create a hash only if it contains key value  
tuples.

> array.inject({}) {|ha, (k, v)| ha[k] = v; ha}

There's absolutely no advantage using inject like this.  
h={}; array.each { |k,v| h[k]=v }  
Is less code and faster.

> ar.to\_enum(:each\_with\_index).inject({}) {|h, (v,k)| h[k]=v;h}

Same here  
h={}; array.each\_with\_index { |k,v| h[k]=v }

Personally I use the following code in my lib:  
# create a hash from an array with keys and an array with values  
# you can set default or provide a block just as with Hash::new  
def Hash.zip(keys, values, default=nil, &block)  
&nbsp;&nbsp;hash = block\_given? ? Hash.new(&block) : Hash.new(default)  
&nbsp;&nbsp;keys.zip(values) { |k,v| hash[k]=v }  
&nbsp;&nbsp;hash  
end

class Array  
# create a hash from an array of [key,value] tuples  
# you can set default or provide a block just as with Hash::new  
# Note: if you use [key, value1, value2, value#], hash[key] will  
# be [value1, value2, value#]  
&nbsp;&nbsp;def to\_hash(default=nil, &block)  
&nbsp;&nbsp;&nbsp;&nbsp;hash = block\_given? ? Hash.new(&block) : Hash.new(default)  
&nbsp;&nbsp;&nbsp;&nbsp;each { |(key, \*value)| hash[key]=\*value }  
&nbsp;&nbsp;&nbsp;&nbsp;hash  
&nbsp;&nbsp;end  
end

Regards  
Stefan

> **···**
>
> > > On Jan 9, 3:31�pm, Holden Holden \<pyar...@gmail.com\> wrote:
> 
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).
