递归Ruby中 - 回归方法本身
问题描述:
我想本身递归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
你能帮我找到解决方案吗?
答
此代码的工作对我来说:
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')
注:
你并不需要定义方法为
self.*
,如果你正在运行这段代码直接在irb
或任何类别外由您定义。我使用了字符串插值(
#{foo}
)而不是连接字符串。追加一个“/*”到文件路径的寻找所有的文件和目录的直属母公司(不嵌套子目录和文件)。
而不是使用2
if
s,在这种情况下可以使用elsif
,因为在每次迭代中只有1个条件可以为真。
答
如果你只是想运用一些方法来子目录中的每个文件,你可以使用:
Dir.glob("**/*").select{ |path| File.file?(path) }.each{ |file| open_file(file) }
解决您的压痕。 –
嗯“堆栈层面太深”大多意味着你有无限递归 – niceman