H
Holden Holden
Hi,
I want to convert an array (with pairs [key,value]) to a hash. After
googling a bit I got:
1) Hash[*array.flatten]
But this is not safe as Array#flatten is recursive.
2) array.inject({}) { |m, e| m[e[0]] = e[1]; m }
Too ugly to consider.
3) Hash[*array.flatten(1)]
That's my own attempt. It only works for Ruby > 1.9.
But I am still wondering why...
- Array objects have no "to_h" method?
- Hasy[*array] don't accept the [key,value] pairs (as Hash#to_a calls
return)?
thanks,
holden
I want to convert an array (with pairs [key,value]) to a hash. After
googling a bit I got:
1) Hash[*array.flatten]
But this is not safe as Array#flatten is recursive.
2) array.inject({}) { |m, e| m[e[0]] = e[1]; m }
Too ugly to consider.
3) Hash[*array.flatten(1)]
That's my own attempt. It only works for Ruby > 1.9.
But I am still wondering why...
- Array objects have no "to_h" method?
- Hasy[*array] don't accept the [key,value] pairs (as Hash#to_a calls
return)?
thanks,
holden