Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 从密钥数组创建哈希_Ruby_Arrays_Hash - Fatal编程技术网

Ruby 从密钥数组创建哈希

Ruby 从密钥数组创建哈希,ruby,arrays,hash,Ruby,Arrays,Hash,我在SO中查看了其他问题,但没有找到我具体问题的答案 我有一个数组: a = ["a", "b", "c", "d"] 我想把这个数组转换成一个散列,其中数组元素成为散列中的键,它们的值都是1。i、 e散列应为: {"a" => 1, "b" => 1, "c" => 1, "d" => 1} 在这里: 根据上面的示例,这假设a=['a',b','c','d']和theValue=1我的解决方案,其中一个:-) ["a", "b", "c", "d"].inject(

我在SO中查看了其他问题,但没有找到我具体问题的答案

我有一个数组:

a = ["a", "b", "c", "d"]
我想把这个数组转换成一个散列,其中数组元素成为散列中的键,它们的值都是1。i、 e散列应为:

{"a" => 1, "b" => 1, "c" => 1, "d" => 1}
在这里:


根据上面的示例,这假设
a=['a',b','c','d']
theValue=1

我的解决方案,其中一个:-)

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

有几种选择:

  • 带块:

    a.to_h { |a_i| [a_i, 1] }
    #=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1}
    
  • +
    至_h

    a.product([1]).to_h
    #=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1}
    
    [a,[1] * a.size].transpose.to_h
    #=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1}
    
  • +
    至_h

    a.product([1]).to_h
    #=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1}
    
    [a,[1] * a.size].transpose.to_h
    #=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1}
    
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

所有这些选项都依赖于Ruby v2.1或更高版本中提供的

将更适合这里。@muistooshort它肯定会是,但我在编写代码时还没有使用到足够的程度。谢谢
:)
我经常使用它,因为块中的额外返回值看起来很孤独:)@muistooshort,更重要的是我总是忘记它,然后得到
未定义的方法[]=
起初
:P
你不需要
展平
,可以接受数组。Hash[]似乎不接受数组不幸的是:Hash[[1,2],[3,4]=>{[1,2]=>[3,4]}@AsfandYarQazi:那么就这样做:
Hash[*[[1,2],[3,4]].展平]
a = ['1','2','33','20']

Hash[a.flatten.map{|v| [v,0]}.reverse]
a = ["a", "b", "c", "d"]
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
a = ['1','2','33','20']

Hash[a.flatten.map{|v| [v,0]}.reverse]
{}.tap{|h| %w(a b c d).each{|x| h[x] = 1}}