如何使用以下数组中的键初始化哈希表?
keys = [ 'a' , 'b' , 'c' ]
期望的哈希值h
应为:
puts h
# { 'a' => nil , 'b' => nil , 'c' => nil }
我们使用Enumerable#each_with_object
和Hash :: []
。
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}
[]' from (irb):29 from C:/RailsInstaller/Ruby1.9.3/bin/irb:12:in
<main>' >>' - user3206440Hash[keys.each_with_object(nil).to_a]
。 - Arup RakshitHash.[]
,不是 Kernel#Hash
,它们是完全不同的方法。 - toro2kputs h #{'a' => [] , 'b' => [] , 'c' => []}
- user3206440Hash[ keys.product([ [] ]) ]
不会像你想的那样工作!它会将哈希表的每个成员初始化为相同的数组值。向其中一个数组添加成员会将相同的成员添加到所有数组中。 - smilingfrogto_h
方法:keys.each_with_object(nil).to_h
使用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
zip
速度更快,但是使用each_with_index
更加清晰和灵活(使用zip
无法生成像{'a' => [], 'b' => [], ...}
这样的哈希表)。在我看来,最好的折中方案是使用product
。 - toro2keach_with_index
,而是each_with_object
。 - Arup Rakshitfruity
gem :-) 顺便说一下,您不需要使用这些前导 _
。嗯,得修复这些 .99999% 的问题... - Marc-André Lafortune=> 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}
keys.map { |k| [k, nil] }
呢? - toro2kkeys.map { |k, _| [k, _] }
- Roman Kiselenko我认为你应该尝试:
x = {}
keys.map { |k, _| x[k.to_s] = _ }
keys.map { |k, _| x[k.to_s] = _ }
,而是 keys.each { |k, _| x[k.to_s] = _ }
就足够了。 - Arup RakshitArray#zip
和 Array#cycle
。Hash[keys.zip([''].cycle)]
# => {"a"=>"", "b"=>"", "c"=>""}