Reputation: 185
I want to return the method in itself
def self.open_folder(file)
Dir.glob(file+"*") do |subfiles|
if File.directory?(subfiles)
open_folder(subfiles) ###Problem here
end
if File.file?(subfiles)
open_file(subfiles)
end
end
end
What I want is to return the "open_folder" to keep open the sub-folder. I got an error
block in open_folder': stack level too deep
Can you help me to find the solution for it?
Upvotes: 0
Views: 82
Reputation: 4920
This code works for me:
def open_file(file)
# Do your stuff here
puts file
end
def open_folder(file)
Dir.glob("#{file}/*") do |subfile|
File.directory?(subfile) ? open_folder(subfile) : open_file(subfile)
end
end
open_folder('path/to/directory')
NOTES:
You don't need to define the methods as self.*
if you are running this code directly in irb
or outside any class defined by you.
I used string interpolation (#{foo}
) instead of concatenating the string.
Appending a '/*' to file path will look for all files and directories directly under the parent (not the nested subdirectories and files).
Instead of using 2 if
s, you can use elsif
in this case as only 1 of the condition can be true in each iteration.
Upvotes: 0
Reputation: 54223
If you just want to apply some method to every file in subdirectories, you could use :
Dir.glob("**/*").select{ |path| File.file?(path) }.each{ |file| open_file(file) }
Upvotes: 1