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.

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.