Project

General

Profile

Actions

Feature #9347

open

Accept non callable argument to detect

Added by marcandre (Marc-Andre Lafortune) about 10 years ago. Updated about 6 years ago.

Status:
Open
Target version:
-
[ruby-core:59482]

Description

Currently, the only argument that Enumerable#detect accepts is a callable object.

Shouldn't we accept non callable objects too?

[42].detect(:not_found){} # => NoMethodError: undefined method `call' for :not_found:Symbol
 # would return :not_found instead.

I'd suggest that if the given argument does not respond_to? :call, then it would be returned as is instead of raising an error as currently.
Wouldn't this be more flexible and possibly more performant?

Inspired by http://stackoverflow.com/questions/20883414/why-does-enumerabledetect-need-a-proc-lambda

Updated by matz (Yukihiro Matsumoto) about 10 years ago

I am afraid that kind of conditional behavior could error prone (e.g. accidental misbehavior when one forget having #call in argument object). I'd rather have #detect with keyword argument, like ary.detect(ifnone: :notfound).

Matz.

Updated by fuadksd (Fuad Saud) about 10 years ago

I think, if it was possible, a call like this ary.detect(:sym) would make more sense by using case equality for comparison instead of #call. It would be useful with regexes for example. There's a ticket proposing this but I can't seem to find it.

Updated by marcandre (Marc-Andre Lafortune) about 10 years ago

  • Assignee changed from matz (Yukihiro Matsumoto) to marcandre (Marc-Andre Lafortune)

I agree, an optional argument would be best. I'll propose a patch. Could we use if_none though?

Actions #5

Updated by naruse (Yui NARUSE) about 6 years ago

  • Target version deleted (2.2.0)
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0