Skip to content

Instantly share code, notes, and snippets.

@tobiashm
Last active December 16, 2015 09:19
Show Gist options
  • Save tobiashm/5412134 to your computer and use it in GitHub Desktop.
Save tobiashm/5412134 to your computer and use it in GitHub Desktop.
Enumerable#try_find - inspired by PrototypeJS Try.these
module Enumerable
def try_find(rescue_type = StandardError)
each do |element|
begin
candidate = element.respond_to?(:call) ? element.call : element
return candidate if candidate
rescue rescue_type
next
end
end
nil
end
end
@tobiashm
Copy link
Author

Example:

  [].try_find
  # => nil
  [42].try_find
  # => 42
  [->{}].try_find
  # => nil
  [->{}, 42].try_find
  # => 42
  [->{raise}, 42].try_find
  # => 42
  [->{raise}, 42].try_find(SyntaxError)
  # => raises RuntimeError 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment