Reputation: 8865
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
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
Reputation: 110755
You can also use Array#product:
['a', 'b', 'c'].product([true]).to_h
#=> {"a"=>true, "b"=>true, "c"=>true}
Upvotes: 1
Reputation: 29174
Another one
> Hash[arr.zip Array.new(arr.size, true)]
# => {"a"=>true, "b"=>true, "c"=>true}
Upvotes: 1
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
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
Reputation: 992
['a', 'b', 'c'].each_with_object({}) { |key, hash| hash[key] = true }
Upvotes: 1
Reputation: 646
Following code will do this:
hash = {}
['a', 'b', 'c'].each{|i| hash[i] = true}
Hope this helps :)
Upvotes: 0
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