0

我正在尝试绑定几个不同的脚本,我在这里和这里注意到了链接文本 尝试获取一个基本脚本,该脚本允许我在给定目录字符和文件扩展名的情况下删除字符或重命名文件。

我正在努力将它们联系在一起。这是我到目前为止的地方。

    require 'fileutils'

define renamer(strip, stripdetails) 
# So this is a strip function.

    def strip(str,char)
   new_str = ""
   str.each_byte do |byte|
      new_str << byte.chr unless byte.chr == char
   end
   new_str
end
# and then retrieve details from user.

#Get directory of files to be changed.
def stripdetails(strip myname)
 puts "Enter Directory containing files"
 STDOUT.flush
 oldname = gets.chomp
 puts "what characters do you want to remove"
 str = gets.chomp
 puts "what file extension do files end in?"
 fileXt = gets.chomp
 end

#And I found this from stackoverflow(I don't have enuff credits to post another hyperlink)
old_file = "oldname"
new_file = strip(oldname,str)
FileUtils.mv(old_file, new_file)
4

2 回答 2

3

这是您的代码的重构。从您的问题或代码中并不完全清楚,但我假设您想从目录中的每个文件名中删除给定的字符。

请注意,您从博客文章中复制的 strip() 方法完全没有必要,因为它是对内置tr()方法的糟糕重新实现。

#Given a directory, renames each file by removing
#specified characters from each filename

require 'fileutils'

puts "Enter Directory containing files"
STDOUT.flush
dir = gets.chomp
puts "what characters do you want to remove from each filename?"
remove = gets.chomp
puts "what file extension do the files end in?"
fileXt = gets.chomp

files = File.join(dir, "*.#{fileXt}")
Dir[files].each do |file|
  new_file = file.tr(remove,"")
  FileUtils.mv(file, new_file)
end
于 2011-01-10T13:02:06.247 回答
0

该程序从不调用您的stripdetails方法。尝试删除“获取要更改的文件目录”块上的def stripdetails..end行,以便代码在同一范围内运行。

于 2011-01-10T05:30:03.677 回答