Skip to content

Instantly share code, notes, and snippets.

@moxley
Created September 18, 2012 22:23
Show Gist options
  • Save moxley/3746335 to your computer and use it in GitHub Desktop.
Save moxley/3746335 to your computer and use it in GitHub Desktop.
Map Enumerable to a Hash instead of an Array
module Enumerable
def map_hash(memo = nil, &block)
i = 0
inject(memo || {}) do |hash, item|
if kind_of?(Hash)
key = item.first
value = item.last
else
key = i
value = item
end
mapped_value = yield(key, value)
hash[mapped_value.first] = mapped_value.last
i += 1
hash
end
end
end
# With a Hash
res = {:foo => 1, :bar => 2}.map_hash do |key, value|
[key, value * 10]
end
p res # {:foo=>10, :bar=>20}
# With an Array:
res = [1, 2].map_hash do |index, value|
[index, value * 10]
end
p res # {0=>10, 1=>20}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment