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?
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.
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.
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.
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.
arr = ["one", "two", "three", "four", "five"]
x = Hash[(0...arr.size).zip arr]
# => {0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With