学习Ruby 随手写的一个小例子。
#罗列目录下所有的文件
class FolderList
#初始化
def initialize()
@itemCount = 0;
end
#罗列
def startList()
p = File.dirname(__FILE__);
puts "dir path: " + p;
puts "==========start list================="
Dir.foreach(p) do |item|
filename = item.class;
if item.index(".png") || item.index(".plist") || item.index(".tps")
puts item;
@itemCount = @itemCount + 1;
end
end
puts "============end list================="
end
#获取目录下所有文件数组
def getFoldFiles()
p = File.dirname(__FILE__);
Dir.entries(p);
end
#count
def getFoldedsCount
return @itemCount;
end
end
#根据文件类型罗列文件
class SubFolderList < FolderList
#初始化
def initialize()
super;
@logger = RecordLogs.new();
end
#根据类型罗列文件
def listFileByType(fType)
files = getFoldFiles();
files.each{|item| if item.index(fType)
puts item;
@logger.addLog(item, "info");
end}
end
end
class RecordLogs
def initialize()
@logInfo = "";
end
def addLog(info, infoType)
@logInfo ="[" + infoType + "]" + "@" + Time.now.inspect + ": " + @logInfo + info + "\n";
f = File.new("log.txt","a+");
f.syswrite(@logInfo);
f.close();
@logInfo = "";
end
end
d = SubFolderList.new();
d.listFileByType(".png");