Method: Array#each
- Defined in:
- array.c
#each {|element| ... } ⇒ self #each ⇒ Object
With a block given, iterates over the elements of self
, passing each element to the block; returns self
:
a = [:foo, 'bar', 2]
a.each {|element| puts "#{element.class} #{element}" }
Output:
Symbol foo
String
Integer 2
Allows the array to be modified during iteration:
a = [:foo, 'bar', 2]
a.each {|element| puts element; a.clear if element.to_s.start_with?('b') }
Output:
foo
With no block given, returns a new Enumerator.
Related: see Methods for Iterating.
2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 |
# File 'array.c', line 2634
VALUE
rb_ary_each(VALUE ary)
{
long i;
ary_verify(ary);
RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
for (i=0; i<RARRAY_LEN(ary); i++) {
rb_yield(RARRAY_AREF(ary, i));
}
return ary;
}
|