Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Iterate thought all .rb (including subfolders) files in the folder

Tags:

ruby

Files structure:

folderA/
 - folder1/
   - file1.rb
   - file2.rb
 - folder2/
   - folder1/
     - file1.rb
   - folder2/
     - file1.rb
 - file1.rb
 - file2.rb

With code below i can iterate only on folderA/file1.rb and folderA/file2.rb

# EDITTED
Dir.glob('folderA/*.rb') do |file|
  puts file
end

Is it possible to iterate over all .rb files (including subfolders) within only using glob (without Dir.foreach(dir)..if..)?

P.S. Ruby v.1.8.6

like image 927
ted Avatar asked Aug 03 '12 15:08

ted


3 Answers

Dir.glob('folderA/**/*.rb') do |file|
  puts file
end

From official docs:

**
Matches directories recursively.

like image 54
hs- Avatar answered Oct 22 '22 13:10

hs-


try this:

Dir.glob('spec/**/*.rb') do |rspec_file|
  puts rspec_file
end

read here about glob

like image 21
davidrac Avatar answered Oct 22 '22 14:10

davidrac


This should work:

Source here: http://ruby-doc.org/stdlib-1.9.3/libdoc/find/rdoc/Find.html

require 'find'

Find.find('spec/') do |rspec_file|
    next if FileTest.directory?(rspec_file)
    if /.*\.rb/.match(File.basename(rspec_file))
        puts rspec_file
    end
end

Tested in ruby 1.8.7

like image 2
jabadie Avatar answered Oct 22 '22 13:10

jabadie