Skip to content

Instantly share code, notes, and snippets.

@jasoncodes
Created December 12, 2011 23:47
Show Gist options
  • Save jasoncodes/1469699 to your computer and use it in GitHub Desktop.
Save jasoncodes/1469699 to your computer and use it in GitHub Desktop.
Enumerable#group_by_many
Enumerable.class_eval do
def group_by_many
{}.tap do |groups|
each do |value|
keys = yield value
keys.each do |key|
group = groups[key] ||= []
group << value
end
end
end
end
end
#!/usr/bin/env ruby
load 'enum_group_by_many.rb'
require 'awesome_print'
Show = Struct.new :name, :cast
# partial cast list for demo purposes :)
shows = [
Show.new(:dr_horrible, [:neil_patrick_harris, :nathan_fillion, :felicia_day]),
Show.new(:firefly, [:nathan_fillion, :jewel_staite, :summer_glau]),
Show.new(:dollhouse, [:eliza_dushku, :summer_glau, :felicia_day]),
]
shows.group_by_many(&:cast).each do |actor, shows|
puts "#{actor}: #{shows.map(&:name).join ', '}"
end
# Output:
#
# neil_patrick_harris: dr_horrible
# nathan_fillion: dr_horrible, firefly
# felicia_day: dr_horrible, dollhouse
# jewel_staite: firefly
# summer_glau: firefly, dollhouse
# eliza_dushku: dollhouse
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment