Ruby 2.6 adds Dir#each_child & Dir#children instance

Tejaswini Chile

By Tejaswini Chile

on August 7, 2018

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
1directory = Dir.new('/Users/tejaswinichile/workspace')
2
3directory.children
4=> ["panda.png", "apple.png", "banana.png", "camera.jpg"]
5

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
1directory = Dir.new('/Users/tejaswinichile/workspace')
2
3directory.each_child { |filename| puts "Currently reading: #{filename}"}
4
5Currently reading: panda.png
6Currently reading: apple.png
7Currently reading: banana.png
8Currently reading: camera.jpg
9=> #<Dir:/Users/tejaswinichile/Desktop>
10

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

1directory = Dir.new('/Users/tejaswinichile/workspace')
2
3directory.each_child
4
5=> #<Enumerator: #<Dir:/Users/tejaswinichile/Desktop>:each_child>
6

Here is relevant commit and discussion for this change.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.