Convert array to hash and initialize value

What is the best way to convert an array

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

      

to the hash

{"one"=>0, "two"=>0, "three"=>0, "four"=>0, "five"=>0}

      

I plan to fill in the "0" with my values ​​later, I just need the technique now.

Thank.

+3


source to share


5 answers


arr.product([0]).to_h

      

or for versions <2.0



Hash[arr.product([0])]

      

+5


source


I don't know if this is the best way:



Hash[arr.map{ |el| [el, 0] }]

      

+5


source


I would do this:

arr.inject({}) { |hash, key| hash.update(key => 0) }

      

+3


source


Hash[ *arr.collect { |v| [ v, 0 ] }.flatten ]

      

+2


source


You can also do

arr.each_with_object({}) {|v, h| h[v] = 1}

      

Where:

  • v

    - the value of each element in the array,
  • h

    represents a hash object
0


source







All Articles