2013-09-24 38 views
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 

感谢您的帮助!

+0

在实际构建chap数组之前计算长度'n',因此x == n == 0.将'n = chap.length.to_i'移到第一次之后。你也不需要to_i – mastaBlasta

+0

作为风格的一个注释,'chapter!='''不是很漂亮。更好的是像'!chapter.empty?'这样的东西,你正在测试'chapter'本身,而不是与另一个字符串进行比较。 'x + = 1'也比'x = x + 1'更可取。 – tadman

回答

3

简单飞行员操作失误:你叫

n = chap.length.to_i 

为时尚早。您必须在放入东西之后获得章节列表的长度。在这里移动该行:

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

puts ('Table of Contents').center lineWidth 

它工作正常。

相关问题