[Feature proposal] Enumerable#group_by should take a second block to allow setting the value

Elixir has a great feature in its Enumerable,group_by/3 function where you can pass 2 functions to it. The first being what to group by (called a key_fun). The second being a function that returns the val (called the value_fun). See: Enum — Elixir v1.14.0

By default the value_fun is a function that does nothing ie. fn x → x end (making its default behaviour the same as Ruby/Rails group_by method)

I would like this functionality in Rails. What do you think, dear community?

(Apologies if this has been brought up before. I did a quick search but found nothing)

Thanks

I think we’ll stick with posts.group_by(&:id).transform_values { |v| v.title.uppercase } — and it’s not because we don’t value_fun! :smile:

Hi David,

For me it is confusing that #group_by does something else besides of grouping, it feels like a side effect to me. In my opinion, the solution that Kasper proposed reveals better the intention of the code.

Thanks for your proposal!