初学者的ruby代码的神秘错误(while循环)

时间:2013-10-02 07:29:20

标签: 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中时它会起作用,但是当我用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>'
编辑:想出来。我所要做的就是出于某种原因将“打印”改为“放置”。

2 个答案:

答案 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。
  • 在方法内部,无法使用两个局部变量inumbers,因为它们是在顶层创建的。因此,您需要在方法内部创建这些变量。

答案 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将内容打印到控制台。并将inumbers变量移至while_var方法。