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.
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.
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.
directory = Dir.new('/Users/tejaswinichile/workspace')
directory.each_child
=> #<Enumerator: #<Dir:/Users/tejaswinichile/Desktop>:each_child>
Here is relevant commit and discussion for this change.
If this blog was helpful, check out our full blog archive.