1

所以这是我的代码。我正在学习 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>'

编辑:想通了。我所要做的就是出于某种原因将“打印”更改为“放置”。

4

2 回答 2

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不能使用,因为它们是在顶层创建的。因此,您需要在方法内本地创建这些变量。
于 2013-10-02T07:30:07.453 回答
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方法中。

于 2013-10-02T07:43:55.007 回答