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.
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
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}
Hash[array.zip([nil].cycle)]
This answer is too short.
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}
array.each_with_object({}) { |i,h| h[i] = nil }