Reputation: 6975
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}
Upvotes: 38
Views: 34945
Reputation: 2259
If your project includes Rails 6 or newer (or you are willing to import ActiveSupport), then you can use Enumerable#index_with:
%i[a b c].index_with { 0 }
# => {a: 0, b: 0, c: 0}
You can optionally pass the array element into the block:
%w[a b c].index_with { |x| x.upcase }
# => {"a" => "A", "b" => "B", "c" => "C"}
Upvotes: 4
Reputation: 35788
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
.
Upvotes: 3
Reputation: 44601
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}
Upvotes: 32
Reputation: 6562
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
Upvotes: 5
Reputation: 24350
My solution, one among the others :-)
a = ["a", "b", "c", "d"]
h = Hash[a.map {|x| [x, 1]}]
Upvotes: 72
Reputation: 7733
a = ["a", "b", "c", "d"]
h = a.inject({}){|h,k| h[k] = 1; h}
#=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1}
Upvotes: 0
Reputation: 80140
a = %w{ a b c d e }
Hash[a.zip([1] * a.size)] #=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1, "e"=>1}
Upvotes: 4
Reputation: 97004
["a", "b", "c", "d"].inject({}) do |hash, elem|
hash[elem] = 1
hash
end
Upvotes: 3