gpt4 book ai didi

ruby 将变量值添加到数组

转载 作者:数据小太阳 更新时间:2023-10-29 08:21:42 25 4
gpt4 key购买 nike

我有一个 Ruby 1.8.6 脚本,它应该采用包含路径的文件名,创建文件夹,然后将文件移动到文件夹中。我有一个数组 created_pa​​ths 来跟踪创建的文件夹(脚本将遍历大量文件)。我在添加到 created_pa​​ths 数组时遇到问题。

created_paths = Array.new
file_name = "first\\second\\third.txt"
parts = file_name.split('\\')
tmp_path = ""
parts.each_with_index { |part,i|
if i == (parts.length - 1)
# copy file to new dir structure
else
tmp_path << part << "/"
if !created_paths.include?(tmp_path)
puts "add to array: #{tmp_path}"
created_paths.push(tmp_path)
# create folder
end
end
}
puts "size=#{created_paths.length}\n"
created_paths.each { |z| print z, "\n " }

当我将 tmp_path 推到 created_pa​​ths 数组时,似乎添加了对 tmp_path 的引用,而不是值。在循环的第二次迭代中,created_pa​​ths.include?(tmp_path) 返回 True。如何将 tmp_path 的值存储在我的数组中,或者我可能缺少范围问题?

我的输出:

add to array: first/
size=1
first/second/

我的异常输出:

add to array: first/
add to array: first/second/
size=2
first/
first/second/

最佳答案

您可以使用 tmp_path.dup 在将字符串推送到数组之前克隆该字符串。

但我不明白你为什么要做所有这些(保留已创建目录的列表)。看看FileUtils#mkdir_p ,你将一个路径传递给你想要创建的目录,它会创建它,连同所有缺失的父目录。

关于ruby 将变量值添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2410055/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com