37

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?

2
  • 2
    What are you ultimately trying to do? If you have those items in an array already, you can access them by their index without building a hash. Jan 25, 2013 at 19:00
  • I have another hash that uses the {index => value} design, and want to merge the hash with the array such that the elements at the given indices are replaced with new values (and new values are added for higher indices). The array to hash conversion is a one-time thing; it will never again, but the hash merging will be done frequently, so I wanted to use Hash#merge!. Though, now that I think about it, maybe it would be easier to just iterate over the hash and modify the array as needed.
    – MxLDevs
    Jan 25, 2013 at 19:03

8 Answers 8

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

x = Hash[(0...arr.size).zip arr]
# => {0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}
4
  • 2
    the last one becomes nil, better start indices with 1 x = Hash[(1...arr.size).zip arr] Jul 22, 2014 at 5:02
  • or if you really need to start with 0, just do x = Hash[(0...arr.size-1).zip arr]
    – Gus
    Jul 5, 2015 at 3:56
  • 4
    x = arr.size.times.zip(arr).to_h Sep 19, 2016 at 16:09
  • Yeah the typo here is that it should be (0..arr.size-1) instead of ... 3 dots.
    – Eric Chen
    Jul 18, 2017 at 0:43
30

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
4
  • Another variant using index_by from ActiveSupport: arr.index_by.with_index { |_, i| i } Jul 2, 2015 at 11:17
  • This is great. Thanx. Oct 16, 2015 at 10:18
  • where i can read more about map.with_index? what other methods are available?
    – Arnold Roa
    Jan 30, 2017 at 0:00
  • @ArnoldRoa. Check class Enumerator: ruby-doc.org/core-2.5.0/Enumerator.html
    – tokland
    Jan 31, 2018 at 18:31
4
x = Hash.new{|h, k| h[k] = arr[k]}
1
  • 2
    I like this but x is empty until you realize the entire collection by accessing all keys. x.keys == [] until you access a key in the hash.
    – Kyle
    Jan 25, 2013 at 19:52
3
%w[one two three four five].map.with_index(1){ |*x| x.reverse }.to_h

Remove (1) if you want to start the index from 0.

0
2

Here is a solution making use of Object#tap, to add values to a newly-created hash:

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

{}.tap do |hsh|
  arr.each_with_index { |item, idx| hsh[idx] = item }
end
#=> {0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}
2

Many good solutions already, just adding a variant (provided you do not have duplicated values):

["one", "two", "three", "four", "five"].map.with_index.to_h.invert
# => {0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}
1

You could monkey patch Array to provide a new method:

class Array
  def to_assoc offset = 0
    # needs recent enough ruby version
    map.with_index(offset).to_h.invert
  end
end

Now you can do:

%w(one two three four).to_assoc(1)
# => {1=>"one", 2=>"two", 3=>"three", 4=>"four"}

This is a common operation I'm doing in Rails apps so I keep this monkey patch around in an initializer.

0

You should go with the map method, it's better and uses less memory. Another solution is with while loop. Good to know this way too, because often you may need to use the while loop.

At example 2, if you want to take each odd index in the an array as a key in the hash, and each even index as a value in the hash

Example 1:

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

def to_hash(arr)
  counter = 0
  new_hash = Hash.new(0)
  while counter < arr.length
    new_hash[counter] = arr[counter]
    counter += 1
  end
  return new_hash
end

puts to_hash(arr)
# Output 
{0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}

Example 2 - Perhaps after getting data as a string, and you split this string to an array, and now you want to convert to key, value.

some_array = ['KBD', 'King Bedroom', 'QBD', 'Queen Bedroom', 'DBD', 'Double Bedroom', 'SGLB', 'Single Bedroom']

def to_hash(arr)
  new_hash = Hash.new(0)
  counter = 0
  while counter < arr.length
    new_hash[arr[counter]] = arr[counter+1]
    counter += 2
  end
  return "#{new_hash}"
end

puts to_key_value_hash(some_array)

# Output 
{"KBD"=>"King Bedroom", "QBD"=>"Queen Bedroom", "DBD"=>"Double Bedroom", "SGLB"=>"Single Bedroom"}

Many ways to do this, but just saying not to forget the while loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.