据我所知,这两个代码片段应该做同样的事情,我对此并不理解。但事实并非如此。有人可以发光一下为什么会这样吗?
我只是想在一个文件夹中查找总文件。此计数也应包括所有嵌套文件夹文件。
这是我的测试用例:
A - File 1 - File 2 - File 3 -- B - File 4 -- D - File 5 -- C - File 6
当我运行此代码段时,
def get_all_files(myfolder, filearray = Array.new)
filearray += myfolder.myfiles.pluck(:id)
myfolder.children.each { |c| get_all_files(c, filearray) }
return filearray
end
它仅返回3个文件。(仅A的文件。)
当我运行此代码段时,
def get_all_files(myfolder, filearray = Array.new)
myfolder.myfiles.pluck(:id).each do |id|
filearray.push(id)
end
myfolder.children.each { |c| get_all_files(c, filearray) }
return filearray
end
它运行的文件的正确数量,这是6。我认为两者.push
并+
都只是一般的Ruby阵列的方法。那么为什么会这样呢?
试试这个:
def get_all_files(myfolder)
folder_files = myfolder.myfiles.pluck(:id))
children_files = myfolder.children.each_with_object([]) do |c,a|
a += get_all_files(c, filearray))
end if my_folder.children.any?
folder_files + children_files
end
问题在于您的线路:
myfolder.children.each { |c| get_all_files(c, filearray) }
它会获取儿童档案,但不会对其进行任何处理。
要查看发生了什么,请考虑以下事项:
def a(h, x=[])
puts h[:name]
puts "x=#{x}, x.object_id 1 = #{x.object_id}"
x += [1]
puts "x=#{x}, x.object_id 2 = #{x.object_id}"
h[:children].each do |g|
a(g,x)
puts h[:name]
puts "x=#{x}, x.object_id 3 = #{x.object_id}"
end
x
end
h = { name: "Bob",
children: [
{ name: "Marsha", children: [] },
{ name: "Bippy" , children: [] }
]
}
a(h)
# Bob
# x=[], x.object_id 1 = 70286033312340
# x=[1], x.object_id 2 = 70286033311720
# Marsha
# x=[1], x.object_id 1 = 70286033311720
# x=[1, 1], x.object_id 2 = 70286033311280
# Bob
# x=[1], x.object_id 3 = 70286033311720
# Bippy
# x=[1], x.object_id 1 = 70286033311720
# x=[1, 1], x.object_id 2 = 70286033310660
# Bob
# x=[1], x.object_id 3 = 70286033311720
# => [1]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句