# Feature request: Array.to\_h

**URL:** <https://rubytalk.org/t/feature-request-array-to-h/4184>\
**Category:** ruby-talk\
**Created:** [17 January 2003 11:05 UTC](https://rubytalk.org/t/feature-request-array-to-h/4184 "2003-01-17T11:05:34Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![Google5](https://avatars.discourse-cdn.com/v4/letter/g/eada6e/32.png) [@Google5](https://rubytalk.org/u/Google5)\
**Post date:** [17 January 2003 11:05 UTC](https://rubytalk.org/t/feature-request-array-to-h/4184/1 "2003-01-17T11:05:34Z")

</div>

I use the following snippet a lot, and think it’s worth including in  
the Ruby built-in Array class.

class Array

def to\_h(default = nil)  
result = Hash.new(default)  
each\_with\_index do |value, index|  
result[index] = value  
end  
result  
end

end

Example usage:

[:a, :b, :c].to\_h # =\> {0=\>:a, 1=\>:b, 2=\>:c}

I often use it in processing comma-separated variable (CSV) files with  
a header row, for example:

header\_row = "year,month,day,price\n"  
index\_of = header\_row.chomp.split(’,’).to\_h.invert

# =\> {“month”=\>1, “price”=\>3, “day”=\>2, “year”=\>0}

data\_row = "2002,1,17,1.5\n"  
cells = data\_row.chomp.split(’,’)

---

<div class="post-metadata">

**Author:** ![David\_Alan\_Black1](https://avatars.discourse-cdn.com/v4/letter/d/278dde/32.png) [@David\_Alan\_Black1](https://rubytalk.org/u/David_Alan_Black1)\
**Post date:** [17 January 2003 12:26 UTC](https://rubytalk.org/t/feature-request-array-to-h/4184/2 "2003-01-17T12:26:01Z")

</div>

Hi –

> I use the following snippet a lot, and think it’s worth including in  
> the Ruby built-in Array class.
> 
> class Array
> 
> def to\_h(default = nil)  
> result = Hash.new(default)  
> each\_with\_index do |value, index|  
> result[index] = value  
> end  
> result  
> end
> 
> end
> 
> Example usage:
> 
> [:a, :b, :c].to\_h # =\> {0=\>:a, 1=\>:b, 2=\>:c}

My inclination would be for a basic #to\_h to operate more like:

%w{a b c d} =\> {“a”=\>“b”, “c”=\>“d”}

and for the method that added in the array indices to be called  
something else. Also, I think you’re doing it backwards 🙂 For one  
thing, if you’ve got duplicate values in your array, your hash will  
end up truncated. Also, I think an indexed #to\_h sort of grows out of  
the idea that an array is, or can be viewed as, a hash whose keys  
happen to be positive integers. That means that you’d want the  
indices to be the _keys_ of the new hash, not the values.

There’s a bunch of versions of this floating around… See the  
thread starting at [http://www.ruby-talk.org/6582](http://www.ruby-talk.org/6582), also an RCR at  
[http://www.rubygarden.com/article.php?sid=61](http://www.rubygarden.com/article.php?sid=61) (which was posted by  
me, though my name isn’t on it; I take full responsibility for the  
idea of the name “hashify”, though I can’t really remember why I  
proposed that name).

David

> **···**
>
> On Fri, 17 Jan 2003, Tom Payne wrote:
> 
> –  
> David Alan Black  
> home: [dblack@candle.superlink.net](mailto:dblack@candle.superlink.net)  
> work: blackdav@shu.edu  
> Web: [http://pirate.shu.edu/~blackdav](http://pirate.shu.edu/~blackdav)

---

<div class="post-metadata">

**Author:** ![Bulat\_Ziganshin](https://avatars.discourse-cdn.com/v4/letter/b/ba8739/32.png) [@Bulat\_Ziganshin](https://rubytalk.org/u/Bulat_Ziganshin)\
**Post date:** [17 January 2003 12:31 UTC](https://rubytalk.org/t/feature-request-array-to-h/4184/3 "2003-01-17T12:31:19Z")

</div>

Hello dblack,

Friday, January 17, 2003, 3:26:01 PM, you wrote:

> > Example usage:
> > 
> > [:a, :b, :c].to\_h # =\> {0=\>:a, 1=\>:b, 2=\>:c}

> My inclination would be for a basic #to\_h to operate more like:

> %w{a b c d} =\> {“a”=\>“b”, “c”=\>“d”}

p Hash[\* %w{a b c d}] # =\> {“a”=\>“b”, “c”=\>“d”}

> **···**
>
> –  
> Best regards,  
> Bulat [mailto:bulatz@integ.ru](mailto:bulatz@integ.ru)

---

<div class="post-metadata">

**Author:** ![Google5](https://avatars.discourse-cdn.com/v4/letter/g/eada6e/32.png) [@Google5](https://rubytalk.org/u/Google5)\
**Post date:** [18 January 2003 16:50 UTC](https://rubytalk.org/t/feature-request-array-to-h/4184/4 "2003-01-18T16:50:21Z")

</div>

[dblack@candle.superlink.net](mailto:dblack@candle.superlink.net) wrote in message news:[Pine.LNX.4.44.0301170722590.17053-100000@candle.superlink.net](mailto:Pine.LNX.4.44.0301170722590.17053-100000@candle.superlink.net)…

> Also, I think you’re doing it backwards 🙂 For one  
> thing, if you’ve got duplicate values in your array, your hash will  
> end up truncated. Also, I think an indexed #to\_h sort of grows out of  
> the idea that an array is, or can be viewed as, a hash whose keys  
> happen to be positive integers. That means that you’d want the  
> indices to be the _keys_ of the new hash, not the values.

The code I posted does use the indicies as the keys:

irb(main):014:0\> h = [:a, :b, :c].to\_h  
=\> {0=\>:a, 1=\>:b, 2=\>:c}  
irb(main):015:0\> h.keys  
=\> [0, 1, 2]

Glad we’re otherwise in agreement 🙂

Tom

---

<div class="post-metadata">

**Author:** ![David\_Alan\_Black1](https://avatars.discourse-cdn.com/v4/letter/d/278dde/32.png) [@David\_Alan\_Black1](https://rubytalk.org/u/David_Alan_Black1)\
**Post date:** [18 January 2003 17:56 UTC](https://rubytalk.org/t/feature-request-array-to-h/4184/5 "2003-01-18T17:56:50Z")

</div>

Hi –

> [dblack@candle.superlink.net](mailto:dblack@candle.superlink.net) wrote in message news:[Pine.LNX.4.44.0301170722590.17053-100000@candle.superlink.net](mailto:Pine.LNX.4.44.0301170722590.17053-100000@candle.superlink.net)…
> 
> > Also, I think you’re doing it backwards 🙂 For one  
> > thing, if you’ve got duplicate values in your array, your hash will  
> > end up truncated. Also, I think an indexed #to\_h sort of grows out of  
> > the idea that an array is, or can be viewed as, a hash whose keys  
> > happen to be positive integers. That means that you’d want the  
> > indices to be the _keys_ of the new hash, not the values.
> 
> The code I posted does use the indicies as the keys:
> 
> irb(main):014:0\> h = [:a, :b, :c].to\_h  
> =\> {0=\>:a, 1=\>:b, 2=\>:c}  
> irb(main):015:0\> h.keys  
> =\> [0, 1, 2]

Whoops, sorry, I inverted your inversion.

> Glad we’re otherwise in agreement 🙂

Almost 🙂 See [http://www.ruby-talk.org/6663](http://www.ruby-talk.org/6663). I seem to evade  
naming any of the variants just “to\_h” (they’re to\_h\_raw, to\_h\_ikeys),  
etc. I’m inclined to think “to\_h” would be what I called “to\_h\_raw”,  
i.e.: [1,2,3,4].to\_h =\> { 1 =\> 2, 3 =\> 4 }, but I’m not sure.

David

> **···**
>
> On Sun, 19 Jan 2003, Tom Payne wrote:
> 
> –  
> David Alan Black  
> home: [dblack@candle.superlink.net](mailto:dblack@candle.superlink.net)  
> work: blackdav@shu.edu  
> Web: [http://pirate.shu.edu/~blackdav](http://pirate.shu.edu/~blackdav)

---

<div class="post-metadata">

**Author:** ![Google5](https://avatars.discourse-cdn.com/v4/letter/g/eada6e/32.png) [@Google5](https://rubytalk.org/u/Google5)\
**Post date:** [20 January 2003 13:13 UTC](https://rubytalk.org/t/feature-request-array-to-h/4184/6 "2003-01-20T13:13:44Z")

</div>

[dblack@candle.superlink.net](mailto:dblack@candle.superlink.net) wrote in message news:[Pine.LNX.4.44.0301181254230.23130-100000@candle.superlink.net](mailto:Pine.LNX.4.44.0301181254230.23130-100000@candle.superlink.net)…

> Almost 🙂 See [http://www.ruby-talk.org/6663](http://www.ruby-talk.org/6663). I seem to evade  
> naming any of the variants just “to\_h” (they’re to\_h\_raw, to\_h\_ikeys),  
> etc. I’m inclined to think “to\_h” would be what I called “to\_h\_raw”,  
> i.e.: [1,2,3,4].to\_h =\> { 1 =\> 2, 3 =\> 4 }, but I’m not sure.

I think of Arrays as mapping integers \>= 0 to values, and of Hashes of  
mapping arbitrary keys to values. So, for me, the POLS for Array.to\_h  
would be to produce a Hash that maps the same keys as the array to the  
same values, i.e [:a, :b].to\_h =\> {0 =\> :a, 1 =\> b}.

Your to\_h ([1,2,3,4].to\_h =\> { 1 =\> 2, 3 =\> 4 }) might be more  
familiar to a PERL programmer. IIRC, in PERL hashes can be written  
[key0, value0, key1, value1, …], but I might be wrong.

N.B. Your implementation of to\_h\_raw from  
[http://www.ruby-talk.org/6663](http://www.ruby-talk.org/6663):

module Enumerable

# The simplest to\_h: array elements are taken two at a time.

# (Not even indices – just elements.)

def to\_h\_raw  
a = dup  
h = {}  
h[a.shift] = a.shift || nil until a.empty?  
h  
end  
end

should really be in the Array class, not the Enumerable module,  
because it uses the shift method: Arrays have this, but Enumerables  
don’t.

An implementation using each (provided by Enumerable):

module Enumerable  
def to\_h\_raw(default = nil)  
result = Hash.new(default)  
key = nil  
index = 0  
each do |element|  
case index % 2  
when 0 then key = element  
when 1 then result[key] = element  
end  
index += 1  
end  
result[key] = nil if index % 2 == 1  
result  
end  
end

[1, 2, 3, 4].to\_h\_raw =\> {1=\>2, 3=\>4}  
[1, 2, 3, 4, 5].to\_h\_raw =\> {5=\>nil, 1=\>2, 3=\>4}

Regards,

Tom

---

<div class="post-metadata">

**Author:** ![David\_Alan\_Black1](https://avatars.discourse-cdn.com/v4/letter/d/278dde/32.png) [@David\_Alan\_Black1](https://rubytalk.org/u/David_Alan_Black1)\
**Post date:** [20 January 2003 15:06 UTC](https://rubytalk.org/t/feature-request-array-to-h/4184/7 "2003-01-20T15:06:49Z")

</div>

Hi –

> [dblack@candle.superlink.net](mailto:dblack@candle.superlink.net) wrote in message news:[Pine.LNX.4.44.0301181254230.23130-100000@candle.superlink.net](mailto:Pine.LNX.4.44.0301181254230.23130-100000@candle.superlink.net)…
> 
> > Almost 🙂 See [http://www.ruby-talk.org/6663](http://www.ruby-talk.org/6663). I seem to evade  
> > naming any of the variants just “to\_h” (they’re to\_h\_raw, to\_h\_ikeys),  
> > etc. I’m inclined to think “to\_h” would be what I called “to\_h\_raw”,  
> > i.e.: [1,2,3,4].to\_h =\> { 1 =\> 2, 3 =\> 4 }, but I’m not sure.
> 
> I think of Arrays as mapping integers \>= 0 to values, and of Hashes of  
> mapping arbitrary keys to values. So, for me, the POLS for Array.to\_h  
> would be to produce a Hash that maps the same keys as the array to the  
> same values, i.e [:a, :b].to\_h =\> {0 =\> :a, 1 =\> b}.
> 
> Your to\_h ([1,2,3,4].to\_h =\> { 1 =\> 2, 3 =\> 4 }) might be more  
> familiar to a PERL programmer. IIRC, in PERL hashes can be written  
> [key0, value0, key1, value1, …], but I might be wrong.

(s/PERL/Perl/ 🙂 Yes, there’s something like that in Perl, but I’m  
thinking more about what’s familiar to a Ruby programmer:

Hash[1,2,3,4] # =\> { 1 =\> 2, 3 =\> 4 }

and taking that as the model for the simplest case of creating a hash  
from a list (literal or array-derived). It’s possible to argue that,  
since we already have the above, we don’t need Array#to\_h to emulate  
it. I suppose I like the sort of organic quality of a to\_h that does  
what Hash[\*arr] does, and then variants that build on that simplest  
construct.

I don’t think POLS is a big issue here. Since there are several  
versions of this in circulation already, whoever uses them pretty much  
has to be willing to read the code and/or documentation anyway 🙂

> N.B. Your implementation of to\_h\_raw from  
> [http://www.ruby-talk.org/6663](http://www.ruby-talk.org/6663):  
> should really be in the Array class, not the Enumerable module,  
> because it uses the shift method: Arrays have this, but Enumerables  
> don’t.

Whoops. Glitches from 60000 messages ago come back to haunt  
me… 🙂

> An implementation using each (provided by Enumerable):
> 
> module Enumerable  
> def to\_h\_raw(default = nil)  
> result = Hash.new(default)  
> key = nil  
> index = 0  
> each do |element|  
> case index % 2  
> when 0 then key = element  
> when 1 then result[key] = element  
> end  
> index += 1  
> end  
> result[key] = nil if index % 2 == 1  
> result  
> end  
> end
> 
> [1, 2, 3, 4].to\_h\_raw =\> {1=\>2, 3=\>4}  
> [1, 2, 3, 4, 5].to\_h\_raw =\> {5=\>nil, 1=\>2, 3=\>4}

You can trim this down a bit. Accessing an uninitialized array  
element will give you nil, so you don’t have to test for that. Here’s  
a version on the very-short-and-probably-inefficient end of the scale  
– there’s probably a nice middle ground somewhere 🙂

module Enumerable  
def to\_h\_raw(default=nil)  
Hash[\*(if (size % 2).zero? then to\_a else to\_a + [default] end)]  
end  
end

p [1, 2, 3, 4].to\_h\_raw # =\> {1=\>2, 3=\>4}  
p [1, 2, 3, 4, 5].to\_h\_raw # =\> {5=\>nil, 1=\>2, 3=\>4}

h = [1,2,3].to\_h\_raw(10)  
p h[3] # =\> 10

David

> **···**
>
> On Mon, 20 Jan 2003, Tom Payne wrote:
> 
> –  
> David Alan Black  
> home: [dblack@candle.superlink.net](mailto:dblack@candle.superlink.net)  
> work: blackdav@shu.edu  
> Web: [http://pirate.shu.edu/~blackdav](http://pirate.shu.edu/~blackdav)
