Ruby 2.5 introduces Dir.children and Dir.each_child

Mohit Natoo

By Mohit Natoo

on November 21, 2017

This blog is part of our  Ruby 2.5 series.

Dir.entries is a method present in Ruby 2.4. It returns the output of shell command ls -a in an array.

1
2> Dir.entries("/Users/john/Desktop/test")
3> => [".", "..", ".config", "program.rb", "group.txt"]
4>

We also have method Dir.foreach which iterates and yields each value from the output of ls -a command to the block.

1
2> Dir.foreach("/Users/john/Desktop/test") { |child| puts child }
3> .
4> ..
5> .config
6> program.rb
7> group.txt
8> test2
9>

We can see that the output includes the directives for current directory and parent directory which are "." and "..".

When we want to have access only to the children files and directories, we do not need the [".", ".."] subarray.

This is a very common use case and we'll probably have to do something like Dir.entries(path) - [".", ".."] to achieve the desired output.

To overcome such issues, Ruby 2.5 introduced Dir.children. It returns the output of ls -a command without the directives for current and parent directories.

1
2> Dir.children("/Users/mohitnatoo/Desktop/test")
3> => [".config", "program.rb", "group.txt"]
4>

Additionally, we can use Dir.each_child method to avoid yielding current and parent directory directives while iterating,

1
2> Dir.each_child("/Users/mohitnatoo/Desktop/test") { |child| puts child }
3> .config
4> program.rb
5> group.txt
6> test2
7>

As noted in the discussion the names were chosen to match with existing methods Pathname#children and Pathname#each_child.

These additions seem like simple features. Well the issue was posted more than two years ago.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.