在ruby中移动数组中引用的文件
我有点困惑。我正在写一个程序来检查一系列文件的md5校验和。那部分效果很好。我认为将这些文件移动到一个重复的文件夹以便于参考/删除会很酷。问题是它一直在失败,它说没有这样的文件或目录,我甚至不确定我是否试图正确地移动这个文件。如果有人不介意看一眼,我会很感激的。提前谢谢在ruby中移动数组中引用的文件,ruby,Ruby,我有点困惑。我正在写一个程序来检查一系列文件的md5校验和。那部分效果很好。我认为将这些文件移动到一个重复的文件夹以便于参考/删除会很酷。问题是它一直在失败,它说没有这样的文件或目录,我甚至不确定我是否试图正确地移动这个文件。如果有人不介意看一眼,我会很感激的。提前谢谢 !/usr/local/bin/ruby require 'find' require 'digest/md5' require 'fileutils' testArray = Dir["**/**/*"]
!/usr/local/bin/ruby
require 'find'
require 'digest/md5'
require 'fileutils'
testArray = Dir["**/**/*"] #create an array based off the contents of the current directory
def checksum(file) #method for calculating the checksum
sumArray = Array.new
dupArray = Array.new
file.each do |file| #Iterate over each entry in the array
digest = Digest::MD5.hexdigest(File.read(file)) # create a MD5 checksum for the file and storeit in the variable digest
dupArray << file if sumArray.include?(digest) # check to see if the item exists in the sumarray already, if not ad to duparray
sumArray << digest unless sumArray.include?(digest) # if it's not already in sumarray, add it in there
end
dupArray
end
this is where my problems start ;)
def duplicateDirectory(file)
file.each do |file|
FileUtils.mv('file', '/duplicate') if Dir.exists?('duplicate')
Dir.mkdir('duplicate')
FileUtils.mv('file', '/duplicate')
end
end
sumTest = checksum(testArray) #pass the test array along to the method written
puts sumTest
duplicateDirectory(sumTest)
您应该删除文件周围的内容,并删除/在副本前面。最好这样重写:
dir = 'duplicate'
Dir.mkdir(dir) if !Dir.exists?(dir)
FileUtils.mv(file, dir)
很抱歉,代码没有正确显示…一切都好了为了将来参考,文本编辑器中有一个代码按钮,它有两个大括号{}。只需突出显示您的文本,然后按那个按钮即可;也许:FileUtils.mkdir_pdir非常感谢,这彻底澄清了我的问题。我相信这是品味的问题。我更喜欢“如果”或“除非”。对我来说,当所有条件分支都一致时,阅读代码就更容易了。我跳过关键字,转到条件本身。少考虑一件事。