2017-03-02 99 views
0

我想本身递归Ruby中 - 回归方法本身

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 

我想是返回“open_folder”保持开放的子文件夹返回的方法。我得到了一个错误

block in open_folder': stack level too deep 

你能帮我找到解决方案吗?

+0

解决您的压痕。 –

+0

嗯“堆栈层面太深”大多意味着你有无限递归 – niceman

回答

0

此代码的工作对我来说:

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') 

注:

  1. 你并不需要定义方法为self.*,如果你正在运行这段代码直接在irb或任何类别外由您定义。

  2. 我使用了字符串插值(#{foo})而不是连接字符串。

  3. 追加一个“/*”到文件路径的寻找所有的文件和目录的直属母公司(不嵌套子目录和文件)。

  4. 而不是使用2 if s,在这种情况下可以使用elsif,因为在每次迭代中只有1个条件可以为真。

+1

你有一个错字:'elsie' :) – niceman

+0

感谢的人..它的作品就像一个魅力。只是#{file} fuq me up tho:D –

+0

固定的拼写错误。谢谢。 :) –

1

如果你只是想运用一些方法来子目录中的每个文件,你可以使用:

Dir.glob("**/*").select{ |path| File.file?(path) }.each{ |file| open_file(file) }