instance method
Array#index
(untyped obj) -> ::Integer?
() { (Elem item) -> ::boolish } -> ::Integer?
() -> ::Enumerator[Elem, ::Integer?]
index(object) → integer or nil
index {|element| ... } → integer or nil
index → new_enumerator
array.c
View on GitHub ↗
static VALUE
rb_ary_index(int argc, VALUE *argv, VALUE ary)
{
VALUE val;
long i;
if (argc == 0) {
RETURN_ENUMERATOR(ary, 0, 0);
for (i=0; i<RARRAY_LEN(ary); i++) {
if (RTEST(rb_yield(RARRAY_AREF(ary, i)))) {
return LONG2NUM(i);
}
}
return Qnil;
}
rb_check_arity(argc, 0, 1);
val = argv[0];
if (rb_block_given_p())
rb_warn("given block not used");
for (i=0; i<RARRAY_LEN(ary); i++) {
VALUE e = RARRAY_AREF(ary, i);
if (rb_equal(e, val)) {
return LONG2NUM(i);
}
}
return Qnil;
}
Alias of #find_index
Returns the zero-based integer index of a specified element, or nil.
With only argument object given, returns the index of the first element element for which object == element:
Example
a = [:foo, 'bar', 2, 'bar'] a.index('bar') # => 1
Returns nil if no such element found.
With only a block given, calls the block with each successive element; returns the index of the first element for which the block returns a truthy value:
Example
a = [:foo, 'bar', 2, 'bar'] a.index {|element| element == 'bar' } # => 1
Returns nil if the block never returns a truthy value.
With neither an argument nor a block given, returns a new Enumerator.
Related: see Methods for Querying.