【发布时间】:2013-12-18 14:09:26
【问题描述】:
我正在创建一个数组: 所有单词的哈希 在所有段落数组中 一个文件夹中所有文件的数组
我相信我已经在所有段落的数组中获得了所有单词的哈希值。但是,为每个文件都这样做,并为每个文件创建一个特定的密钥,这太过分了。
到目前为止,这是我的代码。为文件夹中的所有文件创建唯一数组并将该文件的所有段落数组放入 files 数组时出错。
numberfiles = Dir.glob(File.join('**', '*')).select { |file| File.file?(file) }.count
countfiles+1
# HERE I MAKE THE ARRAY FOR ALL FILES
filesArray = Array.new(numberfiles.to_i, Hash.new)
for j in 0...numberfiles.to_i do
filesArray[j] = Hash.new
end
#now to open all textfiles..
Dir.glob("*.txt").each do |textfile|
lines = File.readlines(textfile)
text = lines.join
paragraph_count = text.split("\.\r").length
#create array with key for every paragraph
testArray = Array.new(paragraph_count.to_i, Hash.new)
for $i in 0...paragraph_count.to_i do
testArray[$i] = Hash.new
end
words_in_each_paragraph = Array.new
i = 0
在这里,我想将所有测试数组保存到文件数组中。那是行不通的:
File.foreach(textfile, "\.\r") do |paragraph|
word_hash = {}
paragraph.split(/\W+/).each_with_object(word_hash) { |w, h|
h[w] = []
}
words_in_each_paragraph << word_hash
testArray[i][:value] = word_hash
filesArray[j][:file] = testArray # HERE IT GOES WRONG
i += 1
end
puts filesArray[1]
end
【问题讨论】:
-
你为什么要粘贴所有代码..只给出痛苦的区域..
-
你为什么使用
for循环?使用each -
Arup,我正在粘贴大部分代码,以便清楚上下文:它是 [currently-not-working-and-not-dynamic ] 数组