Convert a two-dimensional array to a hash : Multidimensional Arrays « Array « Ruby






Convert a two-dimensional array to a hash


squares = [[1,1], [2,4], [3,9]]

results = {}
squares.each { |k,v| results[k] = v }
p results                                             # => {1=>1, 2=>4, 3=>9}

p squares.inject({}) { |h, kv| h[kv[0]] = kv[1]; h }  # => {1=>1, 2=>4, 3=>9}

 








Related examples in the same category

1.What is a multi-dimensional Arrays
2.Combine three arrays to create multi-dimensional array
3.flatten a multi-demensional array
4.transpose a multi-demensional array
5.Size and elements in a two-dimensional array
6.Three dimensional array