1
我刚开始学习Ruby/Rails,并试图编写一个构建数组的程序,然后格式化新数组。我可以在Ruby中使用循环构建数组吗?
它工作到第二个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
感谢您的帮助!
在实际构建chap数组之前计算长度'n',因此x == n == 0.将'n = chap.length.to_i'移到第一次之后。你也不需要to_i – mastaBlasta
作为风格的一个注释,'chapter!='''不是很漂亮。更好的是像'!chapter.empty?'这样的东西,你正在测试'chapter'本身,而不是与另一个字符串进行比较。 'x + = 1'也比'x = x + 1'更可取。 – tadman