Project

General

Profile

Actions

Feature #18366

closed

Enumerator#return_eval

Added by sawa (Tsuyoshi Sawada) almost 3 years ago. Updated almost 3 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-core:106305]

Description

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:

a = ["Hello", "my", "name", "is", "Ruby"]

We either have to repeat the evaluation of the block:

a.max_by(&:length).length # => 5

or create a temporal array:

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:

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"]
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0