Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

class method

Dir.foreach

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.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0