Created
December 12, 2011 23:47
-
-
Save jasoncodes/1469699 to your computer and use it in GitHub Desktop.
Enumerable#group_by_many
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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