---
title: "Ruby 2.6 adds Dir#each_child & Dir#children instance"
description:
  "Ruby 2.6 introduces each_child and children as instance methods to have file
  names in a directory without `.` and `..`"
canonical_url: "https://www.bigbinary.com/blog/ruby-2-6-introduces-dir-each_child-and-dir-children-instance-methods"
markdown_url: "https://www.bigbinary.com/blog/ruby-2-6-introduces-dir-each_child-and-dir-children-instance-methods.md"
---

# Ruby 2.6 adds Dir#each_child & Dir#children instance

Ruby 2.6 introduces each_child and children as instance methods to have file
names in a directory without `.` and `..`

- Author: Tejaswini Chile
- Published: August 7, 2018
- Categories: Ruby 2.6, Ruby

Ruby 2.5 had introduced class level methods
[Dir::each_child](https://ruby-doc.org/core-2.5.1/Dir.html#method-c-each_child)
and [Dir::children](https://ruby-doc.org/core-2.5.1/Dir.html#method-c-children).
We wrote a
[detailed blog](https://blog.bigbinary.com/2017/11/21/ruby-2_5-introduces-dir-children-and-dir-each_child.html)
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

```ruby
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

```ruby
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.

```ruby
directory = Dir.new('/Users/tejaswinichile/workspace')

directory.each_child

=> #<Enumerator: #<Dir:/Users/tejaswinichile/Desktop>:each_child>

```

Here is relevant
[commit](https://github.com/ruby/ruby/commit/6a3a7e9114c3ede47d15f0d2a73f392cfcdd1ea7)
and [discussion](https://bugs.ruby-lang.org/issues/13969) for this change.

## Links

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