好。我是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
答案 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 == '..'