你的程序有两个主要问题。
首先是您在数组arr
中使用了越界值。试试这个a = [1,2,3]; a[a.count]
,你会得到nil
,因为你是在访问a[3]
努力,但在数组中的最后一个元素的索引是2
然后,您使用作为名称fileINDEX.txt
总是2...foobar
指标而没有考虑到一些指标可能已经在您的目录中使用。
额外的问题,你正在使用Dir.entries
,这在我的操作系统提供了更多的定期条目.
和..
应该妥善管理,他们不是你想要操纵。所以,我给你写了一个小小的脚本,希望你觉得它可读,对我来说很有用。你可以改进它! (我在Linux操作系统下)。
# Global var only to stress its importance
$dir = "/home/p/tmp/t1"
Dir.chdir($dir)
# get list of files
fnames = Dir.glob "*"
# get the max index "fileINDEX.txt" already used in the directory
takenIndexes = []
fnames.each do |f|
if f.match /^file(\d+).txt/ then takenIndexes.push $1.to_i; end
end
# get the first free index available
firstFreeIndex = 1
firstFreeIndex = (takenIndexes.max + 1) if takenIndexes.length > 0
# get a range of fresh indexes for possible use
idxs = firstFreeIndex..(firstFreeIndex + (fnames.length))
# i transform the range to list and reverse the order because i want
# to use "pop" to get and remove them.
idxs = idxs.to_a
idxs.reverse!
# rename the files needing to be renamed
puts "--- Renamed files ----"
fnames.each do |f|
# if file has already the wanted format then move to next iteration
next if f.match /^file\d+.txt/
newName = "file" + idxs.pop.to_s + ".txt"
puts "rename: #{f} ---> #{newName}"
File.rename(f, newName)
end