【发布时间】:2010-07-20 16:52:32
【问题描述】:
但我还需要一种方法来重命名它们以防发生冲突。
喜欢if exists? then file.name = "1-"+file.name
或者类似的东西
【问题讨论】:
标签: ruby-on-rails ruby
但我还需要一种方法来重命名它们以防发生冲突。
喜欢if exists? then file.name = "1-"+file.name
或者类似的东西
【问题讨论】:
标签: ruby-on-rails ruby
也许这样的东西适合你:
origin = '/test_dir'
destination = '/another_test_dir'
Dir.glob(File.join(origin, '*')).each do |file|
if File.exists? File.join(destination, File.basename(file))
FileUtils.move file, File.join(destination, "1-#{File.basename(file)}")
else
FileUtils.move file, File.join(destination, File.basename(file))
end
end
【讨论】:
上面的代码有效,但小错误,您正在使用if File.exists?(file),它正在检查文件是否存在于原始文件夹/或子文件夹中,(这没有用,因为它已被读取,因为它已经存在)。您需要检查目标文件夹中是否已存在文件。由于这种语法,“else”永远不会被执行。所有文件都被命名为“1-filename”。
正确的是使用
if File.exists? File.join(destination, File.basename(file))
【讨论】:
另一种选择是在 shell 中运行命令并处理响应:
command = "mv *.* #{ new_directory }/"
response = system command
但是,处理现有文件名等是另一回事。
【讨论】: