Skip to content

Instantly share code, notes, and snippets.

@zachpendleton
Created June 5, 2013 14:55
Show Gist options
  • Select an option

  • Save zachpendleton/5714494 to your computer and use it in GitHub Desktop.

Select an option

Save zachpendleton/5714494 to your computer and use it in GitHub Desktop.
Example of Ruby's Inject method.
Enrollment = Struct.new(:name, :type)
enrollments = [
Enrollment.new('Don Draper', 'Teacher'),
Enrollment.new('Peggy Olson', 'Student'),
Enrollment.new('Pete Campbell', 'Student'),
Enrollment.new('Roger Sterling', 'TA')
]
grouped_enrollments = enrollments.inject({}) do |result, enrollment|
result[enrollment.type] ||= []
result[enrollment.type] << enrollment
result
end
#=> { 'Teacher' => [{name: 'Don Draper' ...}],
# 'Student' => [{name: 'Peggy Olson' ...}, {name: 'Pete Campbell' ...}],
# 'TA' => [{name: 'Roger Sterling' ...}]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment