迭代器不能在简单的循环中工作

时间:2016-09-16 15:32:47

标签: ruby loops iterator

非常烦人的错误,但我还在学习,所以请大家帮忙。 我读了一个文件,做了一个表并迭代它。想知道为什么我的迭代增量在这种类型的循环中不起作用。

nrOfWordsInOneLine_array = Array.new { Hash.new }

iterator = 0
nrOfWordsInOneLine_array.each_with_index do |i, j|
    iterator =+ 1
    puts "Word in line #{j+1} #{iterator} is: #{i.length} and the longest one is #{i.max_by(&:length)} with #{i.max_by(&:length).length} letters"
end

输出:

Word in line 1 1 is: 8 and the longest one is First with 5 letters
Word in line 2 1 is: 6 and the longest one is Second with 6 letters
Word in line 3 1 is: 4 and the longest one is Fourth with 6 letters
Word in line 4 1 is: 2 and the longest one is Fifth with 5 letters

1 个答案:

答案 0 :(得分:4)

iterator =+ 1您错误地+=

您想要iterator += 1,现在您将iterator设置为+1 1