2013-10-02 57 views
1

所以這是我的代碼。我正在學習循環,不知道爲什麼這不起作用。我收到一個錯誤。初學者的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>' 

編輯:想通了。我所要做的只是將「印刷品」改爲「放入」,原因是某種原因。

回答

2

這裏是固定的代碼:

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 
end 

你做了幾個錯誤:

  • 你忘了關while循環。
  • 您使用了#{x}這是不正確的插值語法,但您不需要在這裏插值。只有x。
  • 該方法內部不能使用兩個局部變量inumbers,因爲它們是在頂層創建的。所以你需要在方法內本地創建這些變量。
+2

你會正確格式嗎?爲了說明格式化在發現錯誤方面的重要性? :) –

+0

@SergioTulentsev沒有得到你.. :)也歡迎你.. –

+0

@ArupRakshit修復你的縮進。或者讓我來做。 :) –

2

此代碼應工作:

def while_var(x) 
    i = 0 
    numbers = [] 

    while i < x 
    puts "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 

    numbers 
end 

numbers = 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打印某些內容到控制檯。並將inumbers變量移至while_var方法。