Ruby中的递归 - 返回方法本身

时间:2017-03-02 11:24:02

标签: ruby recursion

我想自己返回方法

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

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

2 个答案:

答案 0 :(得分:1)

如果您只想将某些方法应用于子目录中的每个文件,可以使用:

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

答案 1 :(得分: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. 在这种情况下,您可以使用if,而不是使用2 elsif,因为在每次迭代中只有1个条件可以为真。

相关问题