Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an array to hash, where keys are the indices

Tags:

ruby

I am transforming an array into a hash, where the keys are the indices and values are the elements at that index.

Here is how I have done it

# initial stuff
arr = ["one", "two", "three", "four", "five"]
x = {}

# iterate and build hash as needed
arr.each_with_index {|v, i| x[i] = v}

# result
>>> {0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}

Is there a better (in any sense of the word "better") way to do it?

like image 1000
MxLDevs Avatar asked Jan 25 '13 18:01

MxLDevs


People also ask

How do you turn an array into a hash?

The to_h method is defined in the array class. It works to convert an array to a hash in the form of key-value pairs. The method converts each nested array into key-value pairs. The method also accepts a block.

Can array be hashed?

9.2. Hashes of Arrays. Use a hash of arrays when you want to look up each array by a particular string rather than merely by an index number.

What is difference between keyed array and hash array?

With arrays, the key is an integer, whereas hashes support any object as a key. Both arrays and hashes grow as needed to hold new elements. It's more efficient to access array elements, but hashes provide more flexibility.

What is array in index?

Definition. An array is an indexed collection of data elements of the same type. 1) Indexed means that the array elements are numbered (starting at 0). 2) The restriction of the same type is an important one, because arrays are stored in consecutive memory cells.


2 Answers

arr = ["one", "two", "three", "four", "five"]

x = Hash[(0...arr.size).zip arr]
# => {0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}
like image 81
Kyle Avatar answered Oct 03 '22 00:10

Kyle


Ruby < 2.1:

Hash[arr.map.with_index { |x, i| [i, x] }]
#=> {0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}

Ruby >= 2.1:

arr.map.with_index { |x, i| [i, x] }.to_h
like image 27
tokland Avatar answered Oct 02 '22 22:10

tokland