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

时间:2023-01-24 18:40:25

I just started learning Ruby/Rails, and am trying to write a program that builds an array, then formats the new array.

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

It works up to the second while, and, if I have an array already built, the second part works as well. Is there something I am leaving out?

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

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

Thanks for your help!

谢谢你的帮助!

1 个解决方案

#1


3  

Simple pilot error: You called

简单的飞行员错误:你叫了

n = chap.length.to_i

too early. You have to get the length of the chap list AFTER you put things in it. Move that line here:

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

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

puts ('Table of Contents').center lineWidth

and it works fine.

它工作正常。

#1


3  

Simple pilot error: You called

简单的飞行员错误:你叫了

n = chap.length.to_i

too early. You have to get the length of the chap list AFTER you put things in it. Move that line here:

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

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

puts ('Table of Contents').center lineWidth

and it works fine.

它工作正常。