Project

General

Profile

Actions

Feature #21678

closed

Enumerable#rfind

Feature #21678: Enumerable#rfind

Added by kddnewton (Kevin Newton) about 1 month ago. Updated 9 days ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:123754]

Description

I'd like to introduce rfind to enumerable, which would effectively be the same as reverse_each.find. I've found myself using this a surprising number of times, and have been surprised at its omission. That means either falling back to reverse_each or rindex.

For context, here are a couple of examples of this in the wild:

Updated by matz (Yukihiro Matsumoto) about 1 month ago Actions #2 [ruby-core:123782]

The Enumerable module basically relies on the #each method which only works in the forward direction, and the only way to scan backwards is to convert it to an array once. I agree with Array#rfind (which can be implemented efficiently), but is it necessary for the Enumerable module as well?

Matz.

Updated by kddnewton (Kevin Newton) about 1 month ago Actions #3 [ruby-core:123790]

That makes sense! I'm totally fine with it just being on Array.

Updated by kddnewton (Kevin Newton) 12 days ago Actions #5

  • Status changed from Open to Closed

Applied in changeset git|6147b695870ce82ee3ad5305ce095b63889b8d9d.


Array#rfind

Implement Array#rfind, which is the same as find except from the
other side of the Array. Also implemented Array#find (as opposed to
the generic one on Enumerable because it is significantly faster
and to keep the implementations together.

[Feature #21678]

Updated by etienne (Étienne Barrié) 9 days ago · Edited Actions #6 [ruby-core:124204]

Should we alias detect to also use that Array-specific faster implementation?

>> [].method :detect
=> #<Method: Array(Enumerable)#detect(*)>
>> [].method :find
=> #<Method: Array#find(*)>

Edit: https://github.com/ruby/ruby/pull/15558

Updated by Eregon (Benoit Daloze) 9 days ago Actions #7 [ruby-core:124208]

@etienne Yes, that seems clearly a good fix, could you do it?
(I personally don't like detect but we should keep aliases consistent in performance and behavior)

Updated by kddnewton (Kevin Newton) 9 days ago Actions #8 [ruby-core:124211]

Is this an issue where you could have defined Enumerable#find and now it won't have overwritten Array#find? Should I revert that part of this patch?

Actions

Also available in: PDF Atom