Ruby: Array to hash, without any local variables

心不动则不痛 提交于 2019-12-11 03:58:26

问题


I have an array of strings.

array = ["foo","bar","baz"]

What I'm trying to transform this into is the following:

{"foo"=>nil, "bar"=>nil, "baz" => nil}

I've been doing this with the following:

new_hash = {}
array.each { |k| new_hash[k] = nil }
new_hash

I was wondering if there's any way to accomplish this in a one-liner / without any instance variables.


回答1:


This would work:

new_hash = Hash[array.zip]
# => {"foo"=>nil, "bar"=>nil, "baz"=>nil}
  • array.zip returns [["foo"], ["bar"], ["baz"]]
  • Hash::[] creates a Hash from these keys



回答2:


You can use Hash[]:

1.9.3p194 :004 > Hash[%w[foo bar baz].map{|k| [k, nil]}]
 => {"foo"=>nil, "bar"=>nil, "baz"=>nil} 

or tap

1.9.3p194 :006 > {}.tap {|h| %w[foo bar baz].each{|k| h[k] = nil}}
 => {"foo"=>nil, "bar"=>nil, "baz"=>nil} 



回答3:


Hash[array.zip([nil].cycle)]

This answer is too short.




回答4:


In one line:

array.inject({}) { |new_hash, k| new_hash[k] = nil ; new_hash }

It's not exactly elegant, but it gets the job done.

Is there a reason you need the hash to be already initialized, though? If you just want a hash with a default value of nil, Hash.new can do that.

Hash.new {|h, k| h[k] = nil}



回答5:


array.each_with_object({}) { |i,h| h[i] = nil }


来源:https://stackoverflow.com/questions/11620812/ruby-array-to-hash-without-any-local-variables

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