Skip to content

Instantly share code, notes, and snippets.

@psychocandy
Created February 17, 2013 11:17
Show Gist options
  • Save psychocandy/4971039 to your computer and use it in GitHub Desktop.
Save psychocandy/4971039 to your computer and use it in GitHub Desktop.
An idea for mapping to a hash. Kudos to @dorkalev.
# [1,2,3].map_hash { |x| [x, x*2] }
# => {1=>2, 2=>4, 3=>6}
# { foo: "bar", fiz: "baz" }.map_hash { |k,v| [v,k] }
# => {"bar"=>:foo, "baz"=>:fiz}
module Enumerable
def map_hash
Hash[*self.inject([]) { |arr, a| arr += yield(a) }]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment