如何使用数组中的键初始化哈希?

时间:2014-01-17 13:00:33

标签: ruby hash

如何使用以下数组中的键初始化哈希?

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

所需的哈希h应为:

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

6 个答案:

答案 0 :(得分:11)

我们使用Enumerable#each_with_objectHash::[]

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

或使用Array#product

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

答案 1 :(得分:6)

使用Array#zip的另一种选择:

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

更新:正如Arup Rakshit所建议的那样,建议的解决方案之间的性能比较:

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

结果:

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

答案 2 :(得分:5)

使用新的(Ruby 2.1)to_h

keys.each_with_object(nil).to_h

答案 3 :(得分:1)

=> 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}

答案 4 :(得分:0)

我认为你应该尝试:

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

答案 5 :(得分:0)

如果您需要使用特定的内容初始化哈希,则还可以将Array#zipArray#cycle结合使用:

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