tags:

views:

57

answers:

3
+1  Q: 

Array to Hash Ruby

Okay so here's the deal, I've been googling for ages to find a solution to this and while there are many out there, they don't seem to do the job I'm looking for.

Basically I have an array structured like this

["item 1", "item 2", "item 3", "item 4"] 

I want to convert this to a Hash so it looks like this

{ "item 1" => "item 2", "item 3" => "item 4" }

i.e. the items that are on the 'even' indexes are the keys and the items on the 'odd' indexes are the values.

Any ideas how to do this cleanly? I suppose a brute force method would be to just pull out all the even indexes into a separate array and then loop around them to add the values.

+8  A: 
a = ["item 1", "item 2", "item 3", "item 4"]
h = Hash[*a]

That's it.

Ben Lee
Haha incredible. Cheers man that's exactly what I was looking for.
djhworld
+2  A: 

Just use Hash.[] with the values in the array. For example:

arr = [1,2,3,4]
Hash[*arr] # => gives [1=>2, 3=>4]
Chuck
A: 

Hash has a class method to do this. Try this in irb:

Hash['a','b','c','d']
Nathan Long