---
title: "Ruby 2.5 introduces Dir.children and Dir.each_child"
description:
  "Ruby 2.5 introduces methods new methods to have file names in a directory
  without `.` and `..`"
canonical_url: "https://www.bigbinary.com/blog/ruby-2_5-introduces-dir-children-and-dir-each_child"
markdown_url: "https://www.bigbinary.com/blog/ruby-2_5-introduces-dir-children-and-dir-each_child.md"
---

# Ruby 2.5 introduces Dir.children and Dir.each_child

Ruby 2.5 introduces methods new methods to have file names in a directory
without `.` and `..`

- Author: Mohit Natoo
- Published: November 21, 2017
- Categories: Ruby 2.5, Ruby

[Dir.entries](https://ruby-doc.org/core-2.4.2/Dir.html#entries-method) is a
method present in Ruby 2.4. It returns the output of shell command `ls -a` in an
array.

```ruby

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

We also have method
[Dir.foreach](https://ruby-doc.org/core-2.4.2/Dir.html#foreach-method) which
iterates and yields each value from the output of `ls -a` command to the block.

```ruby

> 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](https://bugs.ruby-lang.org/issues/11302). It
returns the output of `ls -a` command without the directives for current and
parent directories.

```ruby

> 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,

```ruby

> Dir.each_child("/Users/mohitnatoo/Desktop/test") { |child| puts child }
> .config
> program.rb
> group.txt
> test2
>
```

As noted in the [discussion](https://bugs.ruby-lang.org/issues/11302) the names
were chosen to match with existing methods
[Pathname#children](https://ruby-doc.org/stdlib-2.4.2/libdoc/pathname/rdoc/Pathname.html#method-i-children)
and
[Pathname#each_child](https://ruby-doc.org/core-2.4.2/Dir.html#foreach-method).

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

## Links

- [Human page](https://www.bigbinary.com/blog/ruby-2_5-introduces-dir-children-and-dir-each_child)
