From: "funny_falcon (Yura Sokolov)" Date: 2013-06-03T18:29:48+09:00 Subject: [ruby-core:55272] [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 funny_falcon (Yura Sokolov). There are always different ways to work with hash: counters = Hash.new{|h,k| 0} list.each{|e| counters[e]+=1} some_thing_count = counters[some_thing] compared to counters = {} list.each{|e| counters[e] = (counters[e]||0) + 1} raise "THERE IS NO SOME-THING" unless counters[some_thing] So that, group_by should not assume user's needs So, one could assign default proc if he really wants: a = [1, 2, 3, "a", "b"] g = a.group_by {|o| o.class } g.default_proc = proc{|hash, key| hash[key] = [] if key.class==Class } puts "Fixnums: #{g[Fixnum].size}" puts "Strings: #{g[String].size}" puts "Arrays: #{g[Array].size}" if g[0] puts "Zeroes: #{g[0].size}" else raise "NO ZEROES!!!!" end ---------------------------------------- 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-39668 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/