varatis
varatis

Reputation: 14740

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.

Upvotes: 1

Views: 987

Answers (5)

Stefan
Stefan

Reputation: 114158

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

Upvotes: 11

Henry
Henry

Reputation: 423

Hash[array.zip([nil].cycle)]

This answer is too short.

Upvotes: 1

megas
megas

Reputation: 21791

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

Upvotes: 0

Kristján
Kristján

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

user1284966
user1284966

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

Related Questions