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設置爲迭代器變量,請參閱http://www.tutorialspoint.com/ruby/ruby_loops.htm $ i + = 1而不是$ i = + 1 –
爲什麼你需要這個'iterator',因爲它實際上是'j'提供的確切值? – mudasobwa
兩個一般性評論:1)一個Ruby約定是使用「蛇情況」來表示變量和方法的名稱('nr_of_words_in_one_line_array'); 2)'Hash.new'(沒有參數或塊)相當於更常用的'{}'。同樣,你可以寫'']來代替'Array.new'。 –