TIL: Ruby's rfind
I learned about Array#rfind today because Standard Ruby just shipped a lint rule for it. Before Ruby 4.0, if you wanted the last element matching a condition, you’d write:
numbers = [2, 3, 4, 6, 7, 8]
numbers.reverse.find(&:odd?)
#=> 7
That works fine, but reverse allocates a whole new array just to throw it away. rfind does the same thing by iterating backwards without the intermediate allocation:
numbers.rfind(&:odd?)
#=> 7
It lives on Array specifically (not Enumerable) because arrays can be traversed backwards efficiently at the VM level — Enumerable only has #each going forward.
For small arrays the difference is negligible, but it reads better and the intent is clearer. And for large arrays, you’re not creating a throwaway copy in memory.
Thanks to Kevin Newton for the work on this, and to Andy Croll’s writeup for a good reference.