Skip to content

Instantly share code, notes, and snippets.

@kachick
Created January 17, 2012 10:02
Show Gist options
  • Save kachick/1626034 to your computer and use it in GitHub Desktop.
Save kachick/1626034 to your computer and use it in GitHub Desktop.
Hash#maph
# an aproach to http://www.ruby-forum.com/topic/3446541
$VERBOSE = true
class Hash
def maph
return to_enum(__method__) unless block_given?
{}.tap {|hash|
each_pair do |key, value|
key, value = yield key, value
warn "already assigned key '#{key}'" if hash.has_key? key
hash[key] = value
end
}
end
end
list = [4, 5, 6, 4, 5, 6, 6, 7]
p list.group_by{|v|v}.maph{|k, v|[k, v.size]}
@kachick
Copy link
Author

kachick commented Jan 17, 2012

in ruby-1.9.3p0

{4=>2, 5=>2, 6=>3, 7=>1}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment