我的脚本在另一个空数组中返回一个空数组(或者我猜它不是空的,因为另一个数组中还有另一个空数组)。
我有if
条件,检查外部数组是否为空。它说它不是空的,因为它包含一个空数组。我需要帮助才能让它返回false
。我相信最好的方法是检查内部数组是否为空,但我不确定内部数组的创建位置。
这里是检查数组是否为空的方法的代码:
def directory_check(directory_list, save_to_file, today_date, output_file, output_extension, results_file_output)
if directory_list.empty? == false
# changes the working directory to the file output directory for the file
Dir.chdir(save_to_file)
# writes the array contents into a new file
file_name = output_file + "_" + today_date + output_extension
puts Time.now.to_s + " > " + "Saving contents to: " + results_file_output + file_name
puts ""
File.open(file_name, "a+") do |f|
directory_list.each { |element| f.puts(element) }
end
else
puts Time.now.to_s + " > " + "This directory does not contain any subdirectories that are older than 24 hours"
exit
end
end
directory_list
返回[[]]
,empty?
返回false
。
我有另一种方法将项目存储到数组中,但我无法弄清楚为什么数组中有数组:
def store_directories(directories, folder_to_exclude)
# updates search directory for each value for the directories hash
subdir_list = Array.new
directories.each do |element|
directory = "#{element}"
puts Time.now.to_s + " > " + "Updating search directory: " + directory
Dir.chdir(directory)
# outputs only subdirectories with a creation date of older than 24 hours, except for folders names 'Archive'
Dir.glob("*.*").map(&File.method(:realpath))
puts Time.now.to_s + " > " + "Gathering subdirectories..."
puts ""
# Stores the contents of the query into an array and appends to the list for each iteration of the array
subdir_list << Dir.glob("*").map(&File.method(:realpath)).reject {|files|
(not File.directory?(files) &&
(File.mtime(files) < (Time.now - (60*1440))) &&
(not files == directory + folder_to_exclude))
}
puts ""
puts "Adding new folders to the list..."
puts ""
puts "Excluding: " + directory + folder_to_exclude
puts ""
puts subdir_list
puts " "
end
return subdir_list
end
我将一组目录传递给store_directories
方法。
答案 0 :(得分:1)
directory_list
返回[[]]
,empty?
返回false
。
它正常工作并返回正确的值,因为你的directory_list不是空数组,它包含空数组。您需要使用 Array#flatten
> [[]].flatten.empty?
#=> true