3

what is the best way to convert an array of

arr = ["one", "two", "three", "four", "five"]

to hash of

{"one"=>0, "two"=>0, "three"=>0, "four"=>0, "five"=>0}

Iam planning to fillup the '0' with my own values later, I just need the technique now.

Thanks.

5 Answers 5

5
arr.product([0]).to_h

or for versions < 2.0

Hash[arr.product([0])]
Sign up to request clarification or add additional context in comments.

Comments

5

I don't know if it's the best way:

Hash[arr.map{ |el| [el, 0] }]

Comments

3

I would do this:

arr.inject({}) { |hash, key| hash.update(key => 0) }

Comments

2
Hash[ *arr.collect { |v| [ v, 0 ] }.flatten ]

1 Comment

per some very rough benchmarks, of those posted, this one seems to be the fastest for single large arrays, but lags behind when dealing with large numbers of small arrays.
0

You can also do

arr.each_with_object({}) {|v, h| h[v] = 1}

where:

  • v is the value of each element in the array,
  • h represents the hash object

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.