2017-03-02 64 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) }