Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

class method

Dir.foreach

Dir.foreach( dirname ) {| filename | block } → nil
Dir.foreach( dirname, encoding: enc ) {| filename | block } → nil
Dir.foreach( dirname ) → an_enumerator
Dir.foreach( dirname, encoding: enc ) → an_enumerator

Calls the block once for each entry in the named directory, passing the filename of each entry as a parameter to the block.

If no block is given, an enumerator is returned instead.

Example
Dir.foreach("testdir") {|x| puts "Got #{x}" }

produces:

Got .
Got ..
Got config.h
Got main.rb
See also .exist? .getwd .entries .glob also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0