Create a hash from an array of keys
Solution 1
My solution, one among the others :-)
a = ["a", "b", "c", "d"]
h = Hash[a.map {|x| [x, 1]}]
Solution 2
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}
Solution 3
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
Solution 4
a = %w{ a b c d e }
Hash[a.zip([1] * a.size)] #=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1, "e"=>1}
Solution 5
Here:
hash = Hash[a.map { |k| [k, value] }]
This assumes that, per your example above, that a = ['a', 'b', 'c', 'd']
and that value = 1
.
Dennis Mathews
I am a interested in Wireless Connectivity, Mobile Platforms & Applications (iOS, Android). My specialization is in short range wireless protocols - Bluetooth & NFC. Twitter - @Dennis_Mathews Blog - Neosis - Dennis Mathews
Updated on October 14, 2021Comments
-
Dennis Mathews over 2 years
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}