From: "sawa (Tsuyoshi Sawada)" Date: 2021-11-29T05:39:12+00:00 Subject: [ruby-core:106307] [Ruby master Feature#18366] Enumerator#return_eval Issue #18366 has been updated by sawa (Tsuyoshi Sawada). baweaver (Brandon Weaver) wrote in #note-2: > It seems the common usecase you have isolated is similar to the idea of composing some function with the idea of `map`, much like we may see with `filter_map`: > > ```ruby > [1, 2, 3].filter_map { |v| v * 2 if v.even? } Thanks for mentioning that. The use cases of `filter_map` is more complex than what can be done by `Enumerator#return_eval` since it needs both the filtering condition and the mapped value, but indeed, certain sub-cases can be handled: ```ruby ["Ms. Foo", "Dr. Bar", "Baz"].select{_1.match?(/\b[A-Z]\w+\./)}.map{_1[/\b[A-Z]\w+\./]} # => ["Ms.", "Dr."] ["Ms. Foo", "Dr. Bar", "Baz"].select.return_eval{_1[/\b[A-Z]\w+\./]} # => ["Ms.", "Dr."] ``` ---------------------------------------- Feature #18366: Enumerator#return_eval https://bugs.ruby-lang.org/issues/18366#change-94936 * 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: