31
votes

I have looked at other questions in SO and did not find an answer for my specific problem.

I have an array:

a = ["a", "b", "c", "d"]

I want to convert this array to a hash where the array elements become the keys in the hash and all they the same value say 1. i.e hash should be:

{"a" => 1, "b" => 1, "c" => 1, "d" => 1}
9

9 Answers

68
votes

My solution, one among the others :-)

a = ["a", "b", "c", "d"]
h = Hash[a.map {|x| [x, 1]}]
25
votes

There are several options:

  • to_h with block:

    a.to_h { |a_i| [a_i, 1] }
    #=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1}
    
  • product + to_h:

    a.product([1]).to_h
    #=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1}
    
  • transpose + to_h:

    [a,[1] * a.size].transpose.to_h
    #=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1}
    
5
votes
a = ["a", "b", "c", "d"]

4 more options, achieving the desired output:

h = a.map{|e|[e,1]}.to_h
h = a.zip([1]*a.size).to_h
h = a.product([1]).to_h
h = a.zip(Array.new(a.size, 1)).to_h

All these options rely on Array#to_h, available in Ruby v2.1 or higher

4
votes
a = %w{ a b c d e }

Hash[a.zip([1] * a.size)]   #=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1, "e"=>1}
2
votes
["a", "b", "c", "d"].inject({}) do |hash, elem|
  hash[elem] = 1
  hash
end
2
votes

Here:

theHash=Hash[a.map {|k| [k, theValue]}]

This assumes that, per your example above, that a=['a', 'b', 'c', 'd'] and that theValue=1.

0
votes
a = ["a", "b", "c", "d"]
h = a.inject({}){|h,k| h[k] = 1; h}
#=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1}
0
votes
a = ['1','2','33','20']

Hash[a.flatten.map{|v| [v,0]}.reverse]
0
votes
{}.tap{|h| %w(a b c d).each{|x| h[x] = 1}}