Ruby on Rails: nested each loop within while loop generates error

那年仲夏 提交于 2019-12-13 06:01:56

问题


I get a syntax error, when I execute the following code within the rails console: "syntax error, unexpected $end, expecting keyword_end"

range = 2
my_array = Array.new(range)
a = [1]
i = 0
while i < range do
  a.each do |b|
    puts "test"
  end
  i += 1
end

Does anyone know what I am doing wrong? The strange thing is, that the code is working on my server within a ruby file.

Thanks a lot!

tuxware


回答1:


If you're executing it in IRB, it's likely that, as Beerlington said, it's linebreak issues.

It'd explain why it was working in your .rb files but not in IRB...

Solutions? In IRB you can use the semicolon to end a line without executing it... or if you have a long line (which that block of code does not), you can use the classic \ as you would if you were using rails on the command line...

Or... Try pry. It's an IRB replacement that would be an accommodation for your chunk.




回答2:


I have faced similar issue posted here. if we drop (optional) do in the line with a while loop, then this works even in IRB.

range = 2
my_array = Array.new(range)
a = [1]
i = 0
while i < range
  a.each do |b|
    puts "test"
  end
  i += 1
end


来源:https://stackoverflow.com/questions/16452685/ruby-on-rails-nested-each-loop-within-while-loop-generates-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!