所以這是我的代碼。我正在學習循環,不知道爲什麼這不起作用。我收到一個錯誤。初學者的ruby代碼的神祕錯誤(while循環)
i = 0
numbers = []
def while_var(x)
while i < #{x}
print "Entry #{i}: i is now #{i}."
numbers.push(i)
puts "The numbers array is now #{numbers}."
i = i + 1
puts "variable i just increased by 1. It is now #{i}."
end
while_var(6)
puts "Want to see all the entries of the numbers array individually (i.e. not in array format)? Here you go!"
for num in numbers
puts num
end
puts "1337"
這是我的錯誤
1.rb:5: syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('
print "Entry #{i}: i is now #{i}."
^
我不知道這是怎麼一回事。謝謝。
編輯
所以我有這個修改後的代碼
def while_var(x)
i = 0
numbers = []
while i < x
print "Entry #{i}: i is now #{i}."
numbers.push(i)
puts "The numbers array is now #{numbers}."
i = i + 1
puts "variable i just increased by 1. It is now #{i}."
end
puts "next part"
for num in numbers
puts num
end
end
while_var(6)
當我行由行中鍵入它變成IRB它的工作原理,但不是當我運行紅寶石的文件。是什麼賦予了?我得到這個錯誤:
Entry 0: i is now 0.1.rb:8:in `while_var': undefined method `push' for nil:NilClass (NoMethodError)
from 1.rb:23:in `<main>'
編輯:想通了。我所要做的只是將「印刷品」改爲「放入」,原因是某種原因。
你會正確格式嗎?爲了說明格式化在發現錯誤方面的重要性? :) –
@SergioTulentsev沒有得到你.. :)也歡迎你.. –
@ArupRakshit修復你的縮進。或者讓我來做。 :) –