2017-11-25 153 views
-1

这是一个文本文件更名我做了,你把文件中的某些文件夹和程序重新命名他们FILE1.TXT,FILE2.TXT等红宝石文件更名

它可以完成的工作,但它有两个问题

  1. 它给了我这个错误no implicit conversion of nil into String error

  2. 如果我添加新的文件到那里是已经组织文件的文件夹,它们都删除,并创建新文件

是什么导致了这些问题?

i=0 

Dir.chdir 'C:\Users\anon\Desktop\newfolder' 
arr = Dir.entries('C:\Users\anon\Desktop\newfolder') 

for i in 2..arr.count 
if (File.basename(arr[i]) == 'file'+((i-1).to_s)+'.txt') 
puts (arr[i]+' is already renamed to '+'file'+i.to_s) 
else 
File.rename(arr[i],'file'+((i-1).to_s)+'.txt') 
end 
end 

回答

0

你的程序有两个主要问题。

首先是您在数组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