I have an array and I want to convert it to a hash. I want the array elements to be keys, and all values to be the same.
Here is my code:
h = Hash.new
myarr.each do |elem|
h[elem] = 1
end
One alternative would be the following. I don't think it's very different from the solution above.
h = Hash[ *myarr.collect { |elem| [elem, 1] }.flatten ]
Is there a better way I can do this?
First of all, Hash[]
is quite happy to get an array-of-arrays so you can toss out the splat and flatten
and just say this:
h = Hash[myarr.map { |e| [ e, 1 ] }]
I suppose you could use each_with_object
instead:
h = myarr.each_with_object({}) { |e, h| h[e] = 1 }
Another option would be to zip
your myarr
with an appropriate array of 1
s and then feed that to Hash[]
:
h = Hash[myarr.zip([1] * myarr.length)]
I'd probably use the first one though.