This blog is part of our Ruby 2.6 series. Ruby 2.6.0 was released on Dec 25, 2018.

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 returns array of all the filenames except . and .. in the directory. Dir#each_child yields all the filenames and operates on it.

Let’s have a look at examples to understand it better.

directory ='/Users/tejaswinichile/workspace')

=> ["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.

directory ='/Users/tejaswinichile/workspace')

directory.each_child { |filename| puts "Curently reading: #{filename}"}

Curently reading: panda.png
Curently reading: apple.png
Curently reading: banana.png
Curently reading: camera.jpg
=> #<Dir:/Users/tejaswinichile/Desktop>

If we don’t pass any block to each_child, it returns enumerator instead.

directory ='/Users/tejaswinichile/workspace')


=> #<Enumerator: #<Dir:/Users/tejaswinichile/Desktop>:each_child>

Here is relevant commit and discussion for this change.