Reputation: 14740
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.
Upvotes: 1
Views: 987
Reputation: 114158
This would work:
new_hash = Hash[array.zip]
# => {"foo"=>nil, "bar"=>nil, "baz"=>nil}
Upvotes: 11
Reputation: 18803
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}
Upvotes: 2
Reputation: 51
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}
Upvotes: 0