所以这是我的代码。我正在学习 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 时它可以工作,但当我用 ruby 运行文件时它就不行了。是什么赋予了?我收到此错误:
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>'
编辑:想通了。我所要做的就是出于某种原因将“打印”更改为“放置”。