This blog is part of our Ruby 2.6 series.
Ruby 2.5 had introduced class level methods Dir::each_child and Dir::children. We wrote a detailed blog about it.
In Ruby 2.6, same methods are added as instance methods on Dir class.
Dir#children (Link is not available) returns array of all the filenames except
. and .. in the directory. Dir#each_child (Link is not available) yields all
the filenames and operates on it.
Let's have a look at examples to understand it better.
Dir#children
directory = Dir.new('/Users/tejaswinichile/workspace')
directory.children
=> ["panda.png", "apple.png", "banana.png", "camera.jpg"]
Dir#each_child iterates and calls block for each file entry in the given
directory. It uses filename as a parameter to the block.
Dir#each_child
directory = Dir.new('/Users/tejaswinichile/workspace')
directory.each_child { |filename| puts "Currently reading: #{filename}"}
Currently reading: panda.png
Currently reading: apple.png
Currently reading: banana.png
Currently reading: camera.jpg
=> #<Dir:/Users/tejaswinichile/Desktop>
If we don't pass any block to each_child, it returns enumerator instead.
directory = Dir.new('/Users/tejaswinichile/workspace')
directory.each_child
=> #<Enumerator: #<Dir:/Users/tejaswinichile/Desktop>:each_child>
Here is relevant commit and discussion for this change.

Related blogs
- 01MJIT Support in Ruby 2.6March 5, 2019 · Sudeep Tarlekar
- 02Ruby 2.6 Range#cover? accepts Range object as argumentOctober 24, 2018 · Abhay Nikam
- 03Ruby 2.6 adds RubyVM::AST moduleOctober 2, 2018 · Amit Choudhary
- 04Ruby 2.6 adds Enumerable#filter as alias for #selectAugust 28, 2018 · Amit Choudhary