ruby 从一组键创建一个散列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9649228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a hash from an array of keys
提问by Dennis Mathews
I have looked at other questions in SO and did not find an answer for my specific problem.
我查看了 SO 中的其他问题,但没有找到针对我的特定问题的答案。
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:
我想将此数组转换为散列,其中数组元素成为散列中的键,并且所有相同的值都表示为 1。即散列应该是:
{"a" => 1, "b" => 1, "c" => 1, "d" => 1}
回答by Baldrick
My solution, one among the others :-)
我的解决方案,其中之一:-)
a = ["a", "b", "c", "d"]
h = Hash[a.map {|x| [x, 1]}]
回答by potashin
回答by Andreas Rayo Kniep
a = ["a", "b", "c", "d"]
4 more options, achieving the desired output:
4 个更多选项,实现所需的输出:
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
所有这些选项都依赖于Array#to_h,在 Ruby v2.1 或更高版本中可用
回答by coreyward
a = %w{ a b c d e }
Hash[a.zip([1] * a.size)] #=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1, "e"=>1}
回答by Linuxios
Here:
这里:
theHash=Hash[a.map {|k| [k, theValue]}]
This assumes that, per your example above, that a=['a', 'b', 'c', 'd']and that theValue=1.
这假设,根据您上面的示例, thata=['a', 'b', 'c', 'd']和 that theValue=1。
回答by Andrew Marshall
["a", "b", "c", "d"].inject({}) do |hash, elem|
hash[elem] = 1
hash
end
回答by Sandip Ransing
a = ["a", "b", "c", "d"]
h = a.inject({}){|h,k| h[k] = 1; h}
#=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1}
回答by Qmr
a = ['1','2','33','20']
Hash[a.flatten.map{|v| [v,0]}.reverse]
回答by Fumisky Wells
{}.tap{|h| %w(a b c d).each{|x| h[x] = 1}}

