Dennis Mathews
Dennis Mathews

Reputation: 6975

Create a hash from an array of keys

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

Answers (10)

johncip
johncip

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

Linuxios
Linuxios

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

potashin
potashin

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

Fumisky Wells
Fumisky Wells

Reputation: 1209

{}.tap{|h| %w(a b c d).each{|x| h[x] = 1}}

Upvotes: 0

Qmr
Qmr

Reputation: 64

a = ['1','2','33','20']

Hash[a.flatten.map{|v| [v,0]}.reverse]

Upvotes: 0

Andreas Rayo Kniep
Andreas Rayo Kniep

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

Baldrick
Baldrick

Reputation: 24350

My solution, one among the others :-)

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

Upvotes: 72

Sandip Ransing
Sandip Ransing

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

coreyward
coreyward

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

Andrew Marshall
Andrew Marshall

Reputation: 97004

["a", "b", "c", "d"].inject({}) do |hash, elem|
  hash[elem] = 1
  hash
end

Upvotes: 3

Related Questions