Turn an array into keys for hash

浪子不回头ぞ 提交于 2019-12-24 04:48:07

问题


How do I turn an Array into a Hash with values of 0 without an each loop.

For example, given this array:

[1, 2, 3, 4]

I want to get this hash:

{"1"=>0, "2"=>0, "3"=>0, "4"=>0}

回答1:


I'm a fan of simple, and I can never remember exactly how crazy things #inject or Hash constructor arguments work.

array = [1, 2, 3, 4]
hash = {}

array.each do |obj|
  hash[obj.to_s] = 0
end

puts hash.inspect # {"1"=>0, "2"=>0, "3"=>0, "4"=>0}



回答2:


The standard approach is Hash[...]:

Hash[xs.map { |x| [x.to_s, 0] }]

Or Enumerable#mash if you happen to use Facets. I cannot think of something more concise and declarative:

xs.mash { |x| [x.to_s, 0] }



回答3:


array.inject({}) { | a, e | a[e.to_s] = 0; a }

or in a more clean way (thanks to tokland, see the discussion in the comments)

array.inject({}) { | a, e | a.update(e.to_s => 0) }



回答4:


Okay, in reality, I'd use each_with_object, but posting this since it's more fun.

ary = *1..4

hash = Hash[ary.zip ary.dup.fill 0]

hash # => {1=>0, 2=>0, 3=>0, 4=>0}


来源:https://stackoverflow.com/questions/12360108/turn-an-array-into-keys-for-hash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!