From: "sawa (Tsuyoshi Sawada)" Date: 2021-09-20T16:55:36+00:00 Subject: [ruby-core:105355] [Ruby master Feature#18181] Introduce Enumerable#min_with_value, max_with_value, and minmax_with_value Issue #18181 has been updated by sawa (Tsuyoshi Sawada). This is a frequently seen use case. I use code like this: ```ruby %w(abcde fg hi jkl mn).group_by(&:size).min # => [2, ["fg", "hi", "mn"]] ``` and I don't see a strong need to shorten it into a single method although I am not strongly against doing so. However, 1. Its use will be limited if it only picks a single value when the min/max value is not unique. I propose that it should rather hold an array of the corresponding values. 2. I don't think the word "value" is appropriate. By this word, what comes to mind most naturally is the min/max value rather than the enumerated element. Perhaps a word like "element(s)" should be used. 3. I don't think the order of the elements you proposed is appropriate. With `each_with_object`, the enumerated entity is followed by the accumulating object, i.e., the word order matches the order of the elements within the subarray. I think you should follow this practice. Thus, I think your proposal should be modified into something like the following (which looks so similar to what can be done already as I have shown above): ```ruby %w(abcde fg hi jkl mn).min_with_elements(&:size) # => [2, ["fg", "hi", "mn"]] ``` ---------------------------------------- Feature #18181: Introduce Enumerable#min_with_value, max_with_value, and minmax_with_value https://bugs.ruby-lang.org/issues/18181#change-93769 * Author: kyanagi (Kouhei Yanagita) * Status: Open * Priority: Normal ---------------------------------------- PR is https://github.com/ruby/ruby/pull/4874 I propose `Enumerable#min_with_value`, `max_with_value` and `minmax_with_value`. These methods work like this: ``` ruby %w(abcde fg hijk).min_with_value { |e| e.size } # => ['fg', 2] %w(abcde fg hijk).max_with_value { |e| e.size } # => ['abcde', 5] %w(abcde fg hijk).minmax_with_value { |e| e.size } # => [['fg', 2], ['abcde', 5]] ``` Motivation: When I use `Enumerable#min_by`, I sometimes want to get not only the minimum element but also the value from the given block. (e.g.: There are many points. Find the nearest point and get distance to it.) ``` ruby elem = enum.min_by { |e| foo(e) } value = foo(elem) ``` This works, but I'd like to avoid writing foo() twice. (Consider a more complex case.) This can be written without repeated foo() like belows, but it is slightly complicated and needs extra arrays. ``` ruby value, elem = enum.map { |e| [foo(e), e] }.min_by(&:first) ``` If the size of enum is enormous, it is hard to use intermediate arrays. `Enumerable#min_with_value` solves this problem. I think `min_with_value` is the best name I could think of, but any suggestions for better names would be appreciated. -- https://bugs.ruby-lang.org/ Unsubscribe: