I don't understand this, as far as I can tell these two snippets of code should do the same thing. But they aren't. Can someone shine some light as to why this is happening?
I am simply trying to find the total files inside a folder. This count should include all nested folders files also.
Here is my test case:
A
- File 1
- File 2
- File 3
-- B
- File 4
-- D
- File 5
-- C
- File 6
When I run this snippet,
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
It returns only 3 files. (Only A's file.)
When I run this snippet,
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
It runs the proper number of files, which is 6. I thought both .push and + are just normal Ruby array methods. So why does this happen?
file_array += myfolder.children.each { |c| get_all_files(c, filearray) }. You can also deletereturn file_array.