1. 程式人生 > >ruby遍歷資料夾下所有檔案,輸出檔名(migrate報錯處理)

ruby遍歷資料夾下所有檔案,輸出檔名(migrate報錯處理)

1.例子:
//註釋:file_path檔案路徑
def traverse_dir(file_path)
if File.directory? file_path
Dir.foreach(file_path) do |file|
if file !=”.” and file !=”..”
traverse_dir(file_path+”/”+file)
end
end
else
puts “File:#{File.basename(file_path)}, Size:#{File.size(file_path)}”
//註釋:Size可省略
end
end
traverse_dir(‘D:/apache-tomcat’)
//伺服器地址:"#{Rails.root}/db/migrate"
2.實際例子
class SchemaMigration < ActiveRecord::Base
def self.traverse_dir(file_path)
# file_path=”#{Rails.root}/db/migrate”
a=[]
if File.directory? file_path
Dir.foreach(file_path) do |file|
if file !=”.” and file !=”..”
traverse_dir(file_path+”/”+file)
end
end
else
a<<”#{File.basename(file_path)}”
end
b=[]
a.each do |x|
b<