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
dir.c
View on GitHub ↗
static VALUE
dir_foreach(int argc, VALUE *argv, VALUE io)
{
VALUE dir;
RETURN_ENUMERATOR(io, argc, argv);
dir = dir_open_dir(argc, argv);
rb_ensure(dir_each, dir, dir_close, dir);
return Qnil;
}
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.