Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Map array to hash, with custom key and value (See related posts)

This code creates a hash from an array, using a block to determine the keys and values of the hash.

class Array
	def map_to_hash
		map { |e| yield e }.inject({}) { |carry, e| carry.merge! e }
	end
end


Use like this:
[1, 2, 3].map_to_hash { |e| {e => e + 100} } # => {1 => 101, 2 => 102, 3 => 103}

You need to create an account or log in to post comments to this site.


Click here to browse all 5201 code snippets

Related Posts