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 andflattenand just say this:I suppose you could use
each_with_objectinstead:Another option would be to
zipyourmyarrwith an appropriate array of1s and then feed that toHash[]:I'd probably use the first one though.