Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
Array#each
() -> ::Enumerator[Elem, self]
() { (Elem item) -> void } -> self
each {|element| ... } → self
each → new_enumerator
array.c
View on GitHub ↗
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;
}
With a block given, iterates over the elements of self, passing each element to the block; returns self:
Example
a = [:foo, 'bar', 2] a.each {|element| puts "#{element.class} #{element}" }
Output:
Example
Symbol foo String bar Integer 2
Allows the array to be modified during iteration:
Example
a = [:foo, 'bar', 2] a.each {|element| puts element; a.clear if element.to_s.start_with?('b') }
Output:
Example
foo bar
With no block given, returns a new Enumerator.
Related: see Methods for Iterating.