1

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.

2
  • 1
    This question (or very similar) may have appeared like a hundred times in SO. Why on earth was this rejected? bugs.ruby-lang.org/issues/666. A to_hash/mash method is sorely needed. Commented Jul 23, 2012 at 21:54
  • ["foo","bar","baz"].product([nil]).to_h Commented Jun 3, 2015 at 2:28

5 Answers 5

11

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
Sign up to request clarification or add additional context in comments.

Comments

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} 

1 Comment

I withdraw this response in favor of @Stefan's
1
Hash[array.zip([nil].cycle)]

This answer is too short.

Comments

0

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}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.