Alex Rivera | Logout

Create a hash from an array of keys

Asked 2012-03-10T18:57:01.687
40

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}
Edit
Report

1 Answer

72

My solution, one among the others :-)

a = ["a", "b", "c", "d"]
h = Hash[a.map {|x| [x, 1]}]
answered 2012-03-10T19:05:42.727

Your Answer