From: "shan (Shannon Skipper)" Date: 2021-11-29T11:48:38+00:00 Subject: [ruby-core:106311] [Ruby master Feature#18366] Enumerator#return_eval Issue #18366 has been updated by shan (Shannon Skipper). Just a thought, but another option to achieve the aims of this proposal might be to add `return_eval: true` kwargs for Enumerable methods. On the transducer front Brandon mentions, I've wished we had Enumerable kwargs to set the reducing function and an accumulator other than an Array. For example. ``` ruby module TransducerSelect refine Array do def select(acc: [], step: :<<, step_eval: false) unless block_given? return to_enum(__method__) { size if respond_to?(:size) } end each do yielded = yield _1 step_value = step_eval ? yielded : _1 acc.public_send(step, step_value) if yielded end acc end end end using TransducerSelect ["Ms. Foo", "Dr. Bar", "Baz"].select(step_eval: true){_1[/\b[A-Z]\w+\./]} #=> ["Ms.", "Dr."] ["Ms. Foo", "Dr. Bar", "Baz"].select acc: Set.new, step: :add, step_eval: true do _1[/\b[A-Z]\w+\./] end #=> # ["Ms. Foo", "Dr. Bar", "Baz"].select acc: $stdout, step: :puts, step_eval: true do _1[/\b[A-Z]\w+\./] end #>> Ms. #>> Dr. #=> #> ``` ---------------------------------------- Feature #18366: Enumerator#return_eval https://bugs.ruby-lang.org/issues/18366#change-94939 * Author: sawa (Tsuyoshi Sawada) * Status: Open * Priority: Normal ---------------------------------------- Some `Enumerable` methods return one or more of the receiver's elements according to the return value of a block it takes. Often, we want such evaluated value rather than the original element. For example, suppose we want to know the character width sufficient to fit all the strings in an array: ```ruby a = ["Hello", "my", "name", "is", "Ruby"] ``` We either have to repeat the evaluation of the block: ```ruby a.max_by(&:length).length # => 5 ``` or create a temporal array: ```ruby a.map(&:length).max # => 5 ``` both of which seem not to be optimal. I propose to have a method `Enumerator#return_eval` that returns the evaluated value(s) of the block: ```ruby a.max_by.return_eval(&:length) # => 5 a.min_by.return_eval(&:length) # => 2 a.minmax_by.return_eval(&:length) # => [2, 5] ["Ava Davidson", "Benjamin Anderson", "Charlie Baker"] .sort_by.return_eval{_1.split.reverse.join(", ")} # => ["Anderson, Benjamin", "Baker, Charlie", "Davidson, Ava"] ``` -- https://bugs.ruby-lang.org/ Unsubscribe: