Ruby – Create a hash from an array of keys

arrayshashruby

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}

Best Answer

My solution, one among the others :-)

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