Skip to content

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

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.

See also #drop_while #each_index #drop #empty? also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0