Issue #11076 has been updated by baweaver (Brandon Weaver).


mame (Yusuke Endoh) wrote:
> baweaver (Brandon Weaver) wrote:
> > Answer 2: The transformed value, like `group_by`:
> > 
> > ```ruby
> > [1, 2, 3].group_by(&:even?)
> > => {false=>[1, 3], true=>[2]}
> > 
> > [1, 2, 3].tally_by(&:even?)
> > => {false => 2, true => 1}
> > ```
> 
> If we have `tally`, we can implement this behavior easily: `[1, 2, 3].map {|x| x.even? }.tally`.  Is a new method really needed just for a shorthand of this behavior?

It's a common enough that the syntax may be justified. It could be argued that a lot of shorthand expressions aren't technically necessary, but I feel that this makes Ruby Ruby, the ability to say something common with less.

That, and there's established precedent of `count` / `count_by`, `max` / `max_by`, and others that would make this an easily adopted syntax. If it's not adopted I would not be surprised to see a follow-up request to add it.

I would see `tally_by` and other `*_by` methods as the base for their counterparts, such that:

```
[1,2,3].tally == [1,2,3].tally_by(&:itself)
```

Where the non-`*_by` method is effectively the `*_by` method implemented with the `itself` identity function.

----------------------------------------
Feature #11076: Enumerable method count_by
https://bugs.ruby-lang.org/issues/11076#change-76811

* Author: haraldb (Harald Bttiger)
* Status: Closed
* Priority: Normal
* Assignee: nobu (Nobuyoshi Nakada)
* Target version: 
----------------------------------------
I very often use `Hash[array.group_by{|x|x}.map{|x,y|[x,y.size]}]`.

Would be nice with to have a method called `count_by`:

~~~ruby
array = ['aa', 'aA', 'bb', 'cc']
p array.count_by(&:downcase) #=> {'aa'=>2,'bb'=>1,'cc'=>1}
~~~



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>