Ruby: Array to hash, without any local variables

2019-07-16 06:38发布

问题:

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 }