# About array to hash conversion

**URL:** <https://www.ruby-forum.com/t/about-array-to-hash-conversion/125527>\
**Category:** Ruby\
**Created:** [January 9, 2008, 10:31pm UTC](https://www.ruby-forum.com/t/about-array-to-hash-conversion/125527 "2008-01-09T22:31:47Z")\
**Posts on this page:** 14\
**Page:** 1

<div class="post-metadata">

**Author:** ![rbholden](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e99b99/32.png) [@rbholden](https://www.ruby-forum.com/u/rbholden)\
**Post date:** [January 9, 2008, 10:31pm UTC](https://www.ruby-forum.com/t/about-array-to-hash-conversion/125527/1 "2008-01-09T22:31:47Z")

</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.

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

Too ugly to consider.

1. 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:** ![rbholden](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e99b99/32.png) [@rbholden](https://www.ruby-forum.com/u/rbholden)\
**Post date:** [January 10, 2008, 12:59am UTC](https://www.ruby-forum.com/t/about-array-to-hash-conversion/125527/2 "2008-01-10T00:59:37Z")

</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.

---

<div class="post-metadata">

**Author:** ![rbholden](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e99b99/32.png) [@rbholden](https://www.ruby-forum.com/u/rbholden)\
**Post date:** [January 10, 2008, 1:00am UTC](https://www.ruby-forum.com/t/about-array-to-hash-conversion/125527/3 "2008-01-10T01:00:14Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![rbholden](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e99b99/32.png) [@rbholden](https://www.ruby-forum.com/u/rbholden)\
**Post date:** [January 10, 2008, 1:05am UTC](https://www.ruby-forum.com/t/about-array-to-hash-conversion/125527/4 "2008-01-10T01:05:52Z")

</div>

On Jan 9, 3:31 pm, Holden H. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

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

[1, 2, 3].to\_h

---

<div class="post-metadata">

**Author:** ![rbholden](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e99b99/32.png) [@rbholden](https://www.ruby-forum.com/u/rbholden)\
**Post date:** [January 10, 2008, 1:11am UTC](https://www.ruby-forum.com/t/about-array-to-hash-conversion/125527/5 "2008-01-10T01:11:08Z")

</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:  
myArray=[‘255’,‘10’,‘258’,‘08’,‘154’,‘34’] #(etc)  
myHash={}  
c=0  
while c\<=myArray.size  
myHash.store(myArray[c],myArray[c+1])  
c+=2  
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.

---

<div class="post-metadata">

**Author:** ![rbholden](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e99b99/32.png) [@rbholden](https://www.ruby-forum.com/u/rbholden)\
**Post date:** [January 10, 2008, 9:13am UTC](https://www.ruby-forum.com/t/about-array-to-hash-conversion/125527/6 "2008-01-10T09:13:29Z")

</div>

2008/1/9, Holden H. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

> 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.
> 
> 1. array.inject({}) { |m, e| m[e[0]] = e[1]; m }
> 
> Too ugly to consider.

You can do this:

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

Is this nicer according to your standards?

Kind regards

robert

---

<div class="post-metadata">

**Author:** ![rbholden](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e99b99/32.png) [@rbholden](https://www.ruby-forum.com/u/rbholden)\
**Post date:** [January 10, 2008, 6:19am UTC](https://www.ruby-forum.com/t/about-array-to-hash-conversion/125527/7 "2008-01-10T06:19:16Z")

</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.
> 
> 1. 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:** ![rbholden](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e99b99/32.png) [@rbholden](https://www.ruby-forum.com/u/rbholden)\
**Post date:** [January 10, 2008, 10:35am UTC](https://www.ruby-forum.com/t/about-array-to-hash-conversion/125527/8 "2008-01-10T10:35:03Z")

</div>

yermej wrote:

> On Jan 9, 3:31ï¿½pm, Holden H. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) 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

---

<div class="post-metadata">

**Author:** ![rbholden](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e99b99/32.png) [@rbholden](https://www.ruby-forum.com/u/rbholden)\
**Post date:** [January 10, 2008, 10:43am UTC](https://www.ruby-forum.com/t/about-array-to-hash-conversion/125527/9 "2008-01-10T10:43:13Z")

</div>

2008/1/10, Holden H. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

> 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

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

---

<div class="post-metadata">

**Author:** ![rbholden](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e99b99/32.png) [@rbholden](https://www.ruby-forum.com/u/rbholden)\
**Post date:** [January 10, 2008, 10:53am UTC](https://www.ruby-forum.com/t/about-array-to-hash-conversion/125527/10 "2008-01-10T10:53:47Z")

</div>

Robert K. 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

---

<div class="post-metadata">

**Author:** ![rbholden](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e99b99/32.png) [@rbholden](https://www.ruby-forum.com/u/rbholden)\
**Post date:** [January 10, 2008, 5:54pm UTC](https://www.ruby-forum.com/t/about-array-to-hash-conversion/125527/11 "2008-01-10T17:54:13Z")

</div>

Holden H. wrote:

> yermej wrote:
> 
> > On Jan 9, 3:31ï¿½pm, Holden H. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) 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)  
hash = block\_given? ? Hash.new(&block) : Hash.new(default)  
keys.zip(values) { |k,v| hash[k]=v }  
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#]

def to\_hash(default=nil, &block)  
hash = block\_given? ? Hash.new(&block) : Hash.new(default)  
each { |(key, \*value)| hash[key]=\*value }  
hash  
end  
end

Regards  
Stefan

---

<div class="post-metadata">

**Author:** ![rbholden](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e99b99/32.png) [@rbholden](https://www.ruby-forum.com/u/rbholden)\
**Post date:** [March 14, 2015, 4:21am UTC](https://www.ruby-forum.com/t/about-array-to-hash-conversion/125527/12 "2015-03-14T04:21:31Z")

</div>

I don’t think I saw this one:

h = {}; [1,2,3,4].each\_slice(2) {|k,v| h[k]=v}

---

<div class="post-metadata">

**Author:** ![rbholden](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e99b99/32.png) [@rbholden](https://www.ruby-forum.com/u/rbholden)\
**Post date:** [March 15, 2015, 12:30am UTC](https://www.ruby-forum.com/t/about-array-to-hash-conversion/125527/13 "2015-03-15T00:30:59Z")

</div>

# Array objects have no “to\_h” method?

# they do

[[:one, 1], [:two, 2]].to\_h  
=\> {:one=\>1, :two=\>2}

[:one, 1, :two, 2, :buckle\_my, “shoe”, :three].each\_slice(2).map {|a,b|  
[a,b]}.to\_h  
=\> {:one=\>1, :two=\>2, :buckle\_my=\>“shoe”, :three=\>nil}

This works because each\_slice returns an enumerator. cool.

---

<div class="post-metadata">

**Author:** ![rbholden](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e99b99/32.png) [@rbholden](https://www.ruby-forum.com/u/rbholden)\
**Post date:** [March 13, 2015, 6:10pm UTC](https://www.ruby-forum.com/t/about-array-to-hash-conversion/125527/14 "2015-03-13T18:10:27Z")

</div>

I found this. Might be helpful:

[http://programmingbulls.com/ruby-array-hash](http://programmingbulls.com/ruby-array-hash)
