Ticket #4427: group_by_array.patch
| File group_by_array.patch, 1.7 kB (added by andy@tinnedfruit.org, 3 years ago) |
|---|
-
activesupport/lib/active_support/core_ext/enumerable.rb
old new 22 22 # "2006-02-25 -> Transcript" 23 23 # "2006-02-24 -> Transcript, Transcript" 24 24 # "2006-02-23 -> Transcript" 25 def group_by 26 inject({}) do |groups, element| 27 (groups[yield(element)] ||= []) << element 28 groups 29 end 30 end 25 def group_by 26 inject({}) do |groups, element| 27 x = [*yield(element)] 28 x << "" if x.empty? 29 x.each do |e| 30 (groups[e] ||= []) << element 31 end 32 groups 33 end 34 end 31 35 end -
activesupport/test/core_ext/enumerable_test.rb
old new 26 26 objects.group_by {|object| object.name}.each do |name, group| 27 27 assert group.all? {|person| person.name == name} 28 28 end 29 end 30 31 def test_group_by_array 32 Event = Struct.new(:title, :occurs_on) 33 events = [ 34 Event.new("Cooking",["Mon","Tue"]), 35 Event.new("Skiing","Mon"), 36 Event.new("Surfing",["Tue","Wed","Thu"]), 37 Event.new("Knitting",nil), # doesn't occur 38 Event.new("Knitting 2","") # doesn't occur either 39 ] 40 41 events.group_by { |event| event.occurs_on }.each do |day, events| 42 assert events.all? {|event| event.occurs_on == day || event.occurs_on.include?(day) } 43 end 29 44 end 30 45 end