检查目录条目是否是使用ruby的文件或目录

时间:2014-05-05 04:37:16

标签: ruby

好。我是Ruby的大菜鸟。我错过了什么?

我只是想在OS X上遍历一个特定的文件夹,如果一个子条目是我想做某事的目录。

我的代码:

folder = gets.chomp()
Dir.foreach(folder) do |entry|
  puts entry unless File.directory?(entry)
  # unfortunately directory?
  # doesn't work as expected here because everything evaluates to false, but why?  How is this supposed to be done?
end

1 个答案:

答案 0 :(得分:1)

entry仅包含基本名称部分(dirname/basename)。您需要将其与folder一起加入才能获得正确的路径。

folder = gets.chomp()
Dir.foreach(folder) do |entry|
  path = File.join(folder, entry) # <------
  puts entry unless File.directory?(path)
end

除此之外,如果entry...,您可能希望跳过该条目。

  next if entry == '.' || entry == '..'