Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

class method

Dir.foreach

(::path dirname, ?encoding: ::encoding?) -> ::Enumerator[::String, nil]
(::path dirname, ?encoding: ::encoding?) { (::String filename) -> void } -> nil
Dir.foreach(dirpath, encoding: 'UTF-8') {|entry_name| ... } → nil

Calls the block with each entry name in the directory at dirpath; sets the given encoding onto each passed entry_name:

Example
Dir.foreach('/example') {|entry_name| p entry_name }

Output:

Example
"config.h"
"lib"
"main.rb"
".."
"."

Encoding:

Example
Dir.foreach('/example') {|entry_name| p entry_name.encoding; break }
Dir.foreach('/example', encoding: 'US-ASCII') {|entry_name| p entry_name.encoding; break }

Output:

Example
#<Encoding:UTF-8>
#<Encoding:US-ASCII>

See String Encoding.

Returns an enumerator if no block is given.

See also .fchdir .for_fd .exist? .getwd also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0