我已经查看了stackoverflow上的其他问题,但没有找到针对我的特定问题的答案。
我有一个数组:
a = ["a", "b", "c", "d"]
我想将这个数组转换为一个哈希表,其中数组元素成为哈希表中的键,它们的值都是相同的,比如都是1。也就是说,哈希表应该是:
{"a" => 1, "b" => 1, "c" => 1, "d" => 1}
我的解决方案,其中之一 :-)
a = ["a", "b", "c", "d"]
h = Hash[a.map {|x| [x, 1]}]
a = ["a", "b", "c", "d"]
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
a = %w{ a b c d e }
Hash[a.zip([1] * a.size)] #=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1, "e"=>1}
在这里:
hash = Hash[a.map { |k| [k, value] }]
a = ['a', 'b', 'c', 'd']
,并且value = 1
。["a", "b", "c", "d"].inject({}) do |hash, elem|
hash[elem] = 1
hash
end
each_with_object
更合适。 - mu is too short:)
- Andrew Marshall:P
时得到 undefined method []=
。 - Andrew Marshall如果你的项目包括Rails 6或更高版本(或者你愿意导入 ActiveSupport),那么你可以使用 Enumerable#index_with:
%i[a b c].index_with { 0 }
# => {a: 0, b: 0, c: 0}
你可以选择将数组元素传递到块中:
%w[a b c].index_with { |x| x.upcase }
# => {"a" => "A", "b" => "B", "c" => "C"}
a = ["a", "b", "c", "d"]
h = a.inject({}){|h,k| h[k] = 1; h}
#=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1}
{}.tap{|h| %w(a b c d).each{|x| h[x] = 1}}
a = ['1','2','33','20']
Hash[a.flatten.map{|v| [v,0]}.reverse]
flatten
,Hash[]
可以接受一个数组的数组。 - mu is too shortHash[ *[[1, 2], [3, 4]].flatten ]
- Linuxios