0

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?

2
  • fix your indentation. Commented Mar 2, 2017 at 11:25
  • hmmm "stack level too deep" mostly means you have infinite recursion Commented Mar 2, 2017 at 12:07

2 Answers 2

1

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) }
Sign up to request clarification or add additional context in comments.

Comments

0

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.

6 Comments

you have a typo : elsie :)
thanks man.. it works like a charm. just #{file} fuq me up tho :D
Fixed typo. Thanks. :)
No need for elsif. If a path isn't a directory, it's a file.
If it's not clear, @EricDuminil is suggesting you change elsif to else. Being short, you could use a ternary operator: File.directory?(subfile) ? open_folder(subfile) : File.file?(subfile).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.