2016-09-16 42 views
0

非常烦人的错误,但我还在学习,所以请帮助。 我读了一个文件,创建一个表并重复它。想知道为什么我的迭代增量在这种类型的循环中不起作用。迭代器不能在简单的循环中工作

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

更改迭代器中的运算符,您所做的方式是将数字1设置为迭代器变量,请参阅http://www.tutorialspoint.com/ruby/ruby_loops.htm $ i + = 1而不是$ i = + 1 –

+2

为什么你需要这个'iterator',因为它实际上是'j'提供的确切值? – mudasobwa

+0

两个一般性评论:1)一个Ruby约定是使用“蛇情况”来表示变量和方法的名称('nr_of_words_in_one_line_array'); 2)'Hash.new'(没有参数或块)相当于更常用的'{}'。同样,你可以写'']来代替'Array.new'。 –

回答

4

iterator =+ 1你有+=周围走错了路。

你想iterator += 1,现在你正在设置iterator+1这是1