Ender phan
Ender phan

Reputation: 185

Recursive in Ruby - Return method in itself

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

Answers (2)

Jagdeep Singh
Jagdeep Singh

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:

  1. 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.

  2. I used string interpolation (#{foo}) instead of concatenating the string.

  3. Appending a '/*' to file path will look for all files and directories directly under the parent (not the nested subdirectories and files).

  4. Instead of using 2 ifs, you can use elsif in this case as only 1 of the condition can be true in each iteration.

Upvotes: 0

Eric Duminil
Eric Duminil

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

Related Questions