Niels Kristian
Niels Kristian

Reputation: 8865

Create hash with keys from array and a standard value

I have an array like this:

['a', 'b', 'c']

What is the simplest way to turn it into:

{'a' => true, 'b' => true, 'c' => true}

true is just a standard value that values should hold.

Upvotes: 2

Views: 117

Answers (8)

Aaron Hall
Aaron Hall

Reputation: 395913

If you switch to Python, it's this easy:

>>> l = ['a', 'b', 'c']
>>> d = dict.fromkeys(l, True)
>>> d
{'a': True, 'c': True, 'b': True}

Upvotes: 0

Cary Swoveland
Cary Swoveland

Reputation: 110755

You can also use Array#product:

['a', 'b', 'c'].product([true]).to_h
  #=> {"a"=>true, "b"=>true, "c"=>true}

Upvotes: 1

Santhosh
Santhosh

Reputation: 29174

Another one

> Hash[arr.zip Array.new(arr.size, true)]
# => {"a"=>true, "b"=>true, "c"=>true}

Upvotes: 1

Patrick Oscity
Patrick Oscity

Reputation: 54734

Depending on your specific needs, maybe you do not actually need to initialize the values. You could simply create a Hash with a default value of true this way:

h = Hash.new(true)
#=> {}

Then, when you try to access a key that was not present before:

h['a']
#=> true

h['b']
#=> true

Pros: less memory used, faster to initialize.

Cons: does not actually store keys so the hash will be empty until some other code stores values in it. This will only be a problem if your program relies on reading the keys from the hash or wants to iterate over the hash.

Upvotes: 2

Arup Rakshit
Arup Rakshit

Reputation: 118299

How about below ?

2.1.0 :001 > ['a', 'b', 'c'].each_with_object(true).to_h
 => {"a"=>true, "b"=>true, "c"=>true} 

Upvotes: 7

amenzhinsky
amenzhinsky

Reputation: 992

['a', 'b', 'c'].each_with_object({}) { |key, hash| hash[key] = true }

Upvotes: 1

Himesh
Himesh

Reputation: 646

Following code will do this:

hash = {}
['a', 'b', 'c'].each{|i| hash[i] = true}

Hope this helps :)

Upvotes: 0

BroiSatse
BroiSatse

Reputation: 44725

Try:

Hash[ary.map {|k| [k, true]}]

Since Ruby 2.0 you can use to_h method:

ary.map {|k| [k, true]}.to_h

Upvotes: 3

Related Questions