我可以在Ruby中使用循环构建数组吗?

时间:2013-09-24 17:46:26

标签: ruby-on-rails ruby arrays

我刚开始学习Ruby / Rails,我正在尝试编写一个构建数组的程序,然后格式化新数组。

它适用于第二个while,如果我已经构建了一个数组,那么第二部分也可以工作。有什么我要遗漏的吗?

chap = []
page = []
lineWidth = 80
x = 0
n = chap.length.to_i
puts 'chapter?'
chapter = gets.chomp
while chapter != ''
  chap.push chapter
  puts 'page?'
  pg = gets.chomp
  page.push pg
  puts 'chapter?'
  chapter = gets.chomp
end
puts ('Table of Contents').center lineWidth
puts ''
while x < n
 puts ('Chapter ' + (x+1).to_s + ' ' + chap[x]).ljust(lineWidth/2) +(' page ' + page[x]).rjust(lineWidth/2)
 x = x + 1
end

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

简单的飞行员错误:你打电话

n = chap.length.to_i
太早了。你把东西放进去之后你必须得到破解清单的长度。在这里移动该行:

    ...
    puts 'chapter?'
    chapter = gets.chomp
end
n = chap.length.to_i

puts ('Table of Contents').center lineWidth

它工作正常。