Issue #8478 has been updated by phiggins (Pete Higgins).


duerst (Martin Dürst) wrote:
> I don't think I agree with the proposer. The example looks good, but what about something like:
> 
> a = [1, 2, 3, "a", "b"]
> g = a.group_by {|o| o.class }
> 
> puts "Fixnums: #{g[Fixnum].size}"
> puts "Strings: #{g[String].size}"
> puts "Zeroes: #{g[0].size}"
> 
> In other words, it might be desirable to return an empty array for a group key that is part of the collection that we group over (classes in the example), but it'd be better to cause an error for group keys that are outside of the collection (i.e., not classes in the example).
> 
> That would mean that the default proc should (for this example) be something like
>     {|hash, key| hash[key] = [] if key.class==Class }
> Of course, that cannot be part of Ruby, unless maybe as a third argument of some form to group_by.

I certainly didn't intend for the default value to have some idea of the type of comparison done by the call to group_by, that seems to go well outside the scope of group_by and just general ruby semantics. It seems counter intuitive to me that while the point of the method is to return a hash of arrays, the return value would produce either an array with some values in it or nil. It returning a hash that produced arrays with some values in them or an empty arrays means you're only dealing with one type of thing, an array.
----------------------------------------
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-39688

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 `<main>': 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/