Method: Enumerable#find_index

Defined in:
enum.c

#find_index(object) ⇒ Integer? #find_index {|element| ... } ⇒ Integer? #find_indexObject

Returns the index of the first element that meets a specified criterion, or nil if no such element is found.

With argument object given, returns the index of the first element that is == object:

['a', 'b', 'c', 'b'].find_index('b') # => 1

With a block given, calls the block with successive elements; returns the first element for which the block returns a truthy value:

['a', 'b', 'c', 'b'].find_index {|element| element.start_with?('b') } # => 1
{foo: 0, bar: 1, baz: 2}.find_index {|key, value| value > 1 }         # => 2

With no argument and no block given, returns an Enumerator.

Overloads:

  • #find_index(object) ⇒ Integer?

    Returns:

  • #find_index {|element| ... } ⇒ Integer?

    Yields:

    • (element)

    Returns:



450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
# File 'enum.c', line 450

static VALUE
enum_find_index(int argc, VALUE *argv, VALUE obj)
{
    struct MEMO *memo;  /* [return value, current index, ] */
    VALUE condition_value = Qnil;
    rb_block_call_func *func;

    if (argc == 0) {
        RETURN_ENUMERATOR(obj, 0, 0);
        func = find_index_iter_i;
    }
    else {
        rb_scan_args(argc, argv, "1", &condition_value);
        if (rb_block_given_p()) {
            rb_warn("given block not used");
        }
        func = find_index_i;
    }

    memo = MEMO_NEW(Qnil, condition_value, 0);
    rb_block_call(obj, id_each, 0, 0, func, (VALUE)memo);
    return memo->v1;
}