From: "phiggins (Pete Higgins)" Date: 2013-06-04T15:51:13+09:00 Subject: [ruby-core:55294] [ruby-trunk - Feature #8478] The hash returned by Enumerable#group_by should have an empty array for its default value Issue #8478 has been updated by phiggins (Pete Higgins). marcandre (Marc-Andre Lafortune) wrote: > First of, it's a really bad idea to set the default of a hash to a mutable object: Yes, I didn't consider the problem of returning the same array for every key, and that would have to be changed if this were to be seriously considered. > Assuming now that your request was instead to change the default proc to {|hash, key| hash[key] = []}, which would not cause the problem above, you still have the problem of incompatibility. It seems like some appropriate milestone like 2.1 might be an acceptable place to make such an incompatible change. ---------------------------------------- Feature #8478: The hash returned by Enumerable#group_by should have an empty array for its default value https://bugs.ruby-lang.org/issues/8478#change-39687 Author: phiggins (Pete Higgins) Status: Open Priority: Normal Assignee: matz (Yukihiro Matsumoto) Category: Target version: Without this patch, nil checks might need to be done on the return value of Enumerable#group_by: $ cat test_group_by.rb a = [1, 2, 3, "a", "b"] g = a.group_by {|o| o.class } puts "Fixnums: #{g[Fixnum].size}" puts "Strings: #{g[String].size}" puts "Arrays: #{g[Array].size}" $ ruby test_group_by.rb Fixnums: 3 Strings: 2 test_group_by.rb:6:in `
': undefined method `size' for nil:NilClass (NoMethodError) This patch adds a default value of an empty array to the hash returned by Enumerable#group_by, so the script above will work: $ ./ruby -I.:lib test_group_by.rb Fixnums: 3 Strings: 2 Arrays: 0 -- http://bugs.ruby-lang.org/