所以这是我的代码。我正在学习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>'
编辑:想出来。我所要做的就是出于某种原因将“打印”改为“放置”。
答案 0 :(得分: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。i
和numbers
,因为它们是在顶层创建的。因此,您需要在方法内部创建这些变量。答案 1 :(得分: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
将内容打印到控制台。并将i
和numbers
变量移至while_var
方法。