Project

General

Profile

Actions

Feature #12350

open

Introduce Array#find! that raises an error if element not found

Added by ka8725 (Andrey Koleshko) over 8 years ago. Updated over 8 years ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:75365]

Description

It would be great to have some function (like Hash#fetch) for Array that raises an exception if element not found by passed block in find.

For example:

[].find! { |el| el == 1 }
=> ElementError: element not found

I just noticed that there are many cases when it's needed to raise an exception (because this is exceptional situation) if an element not found.

Currently I just define methods like this one:

def find_price!(size)
  found_price = prices.find { |p| p.key == size }
  fail "Price for #{size} not found" unless found_price
  found_price
end
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0