RockPaperScissors

LizardSpock

Super Simple Ruby List Directory Contents

| Comments

A very simple Ruby way for listing files in a directory is the glob function:

#!/usr/bin/env ruby

@directory_to_list = '/some/path/'
files = Dir.glob(@directory_to_list + '*')

files.each do |x|
   puts x
end

To avoid the separate each block, select could be used to iterate over the results. Used below with entries instead of glob.

Dir.entries(@directory_to_list).select do |f| 
  puts f
end

NB Dir.glob takes a pattern as an argument, Dir.entries takes a path.

Comments