我正在尝试将我在这里注意到的几个不同的脚本绑在一起link text 尝试获取一个基本脚本,允许我在给定目录字符和文件扩展名的情况下剥离字符或重命名文件。
我正在努力把它们捆绑在一起。这是我到目前为止的地方。
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)
答案 0 :(得分: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
答案 1 :(得分:0)
此程序从不调用您的stripdetails
方法。尝试删除“获取要更改的文件的目录”块上的def stripdetails..
和end
行,以便代码在相同的范围内运行。