2

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.

8 Answers 8

7

How about below ?

2.1.0 :001 > ['a', 'b', 'c'].each_with_object(true).to_h
 => {"a"=>true, "b"=>true, "c"=>true} 
Sign up to request clarification or add additional context in comments.

Comments

3

Try:

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

Since Ruby 2.0 you can use to_h method:

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

Comments

2

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.

Comments

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

Comments

1

Another one

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

Comments

1

You can also use Array#product:

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

Comments

0

Following code will do this:

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

Hope this helps :)

Comments

0

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}

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.