user3206440
user3206440

Reputation: 5049

How to initialize a hash with keys from an array?

How to initialize a hash with keys from an array like the following?

keys = [ 'a' , 'b' , 'c' ]

Desired hash h should be:

puts h 
# { 'a' => nil , 'b' => nil , 'c' => nil }

Upvotes: 14

Views: 8420

Answers (6)

schmijos
schmijos

Reputation: 8695

If you need to initialize the hash with something specific, you could also use Array#zip with Array#cycle:

Hash[keys.zip([''].cycle)]
# => {"a"=>"", "b"=>"", "c"=>""}

Upvotes: 0

toro2k
toro2k

Reputation: 19230

Another alternative using Array#zip:

Hash[keys.zip([])]
# => {"a"=>nil, "b"=>nil, "c"=>nil}

Update: As suggested by Arup Rakshit here's a performance comparison between the proposed solutions:

require 'fruity'

ary = *(1..10_000)

compare do
  each_with_object {  ary.each_with_object(nil).to_a  }
  product          {  ary.product([nil])  }
  zip              {  ary.zip([])  }
  map              {  ary.map { |k| [k, nil] }  }
end

The result:

Running each test once. Test will take about 1 second.
zip is faster than product by 19.999999999999996% ± 1.0%
product is faster than each_with_object by 30.000000000000004% ± 1.0%
each_with_object is similar to map

Upvotes: 6

Kushal
Kushal

Reputation: 218

I think you should try:

x = {}
keys.map { |k, _| x[k.to_s] = _ }

Upvotes: 0

steenslag
steenslag

Reputation: 80065

Using the new (Ruby 2.1) to_h:

keys.each_with_object(nil).to_h

Upvotes: 10

Arup Rakshit
Arup Rakshit

Reputation: 118261

Here we go using Enumerable#each_with_object and Hash::[].

 keys = [ 'a' , 'b' , 'c' ]
 Hash[keys.each_with_object(nil).to_a]
 # => {"a"=>nil, "b"=>nil, "c"=>nil}

or Using Array#product

keys = [ 'a' , 'b' , 'c' ]
Hash[keys.product([nil])]
# => {"a"=>nil, "b"=>nil, "c"=>nil}

Upvotes: 16

Roman Kiselenko
Roman Kiselenko

Reputation: 44360

=> keys = [ 'a' , 'b' , 'c' ]
=> Hash[keys.map { |x, z| [x, z] }]
# {"a"=>nil, "b"=>nil, "c"=>nil}

=> Hash[keys.map { |x| [x, nil] }]
# {"a"=>nil, "b"=>nil, "c"=>nil}

=> Hash[keys.map { |x, _| [x, _] }]
# {"a"=>nil, "b"=>nil, "c"=>nil}

Upvotes: 1

Related Questions