Search code examples
rubyenumerable

Ruby: Array to hash, without any local variables


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.


Solution

  • 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