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.
> Dir.entries("/Users/john/Desktop/test")
> => [".", "..", ".config", "program.rb", "group.txt"]
>
We also have method
Dir.foreach which
iterates and yields each value from the output of ls -a
command to the block.
> Dir.foreach("/Users/john/Desktop/test") { |child| puts child }
> .
> ..
> .config
> program.rb
> group.txt
> test2
>
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.
> Dir.children("/Users/mohitnatoo/Desktop/test")
> => [".config", "program.rb", "group.txt"]
>
Additionally, we can use Dir.each_child
method to avoid yielding current and
parent directory directives while iterating,
> Dir.each_child("/Users/mohitnatoo/Desktop/test") { |child| puts child }
> .config
> program.rb
> group.txt
> test2
>
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.
If this blog was helpful, check out our full blog archive.