gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:20:40 25 4
gpt4 key购买 nike

我刚开始学习 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

感谢您的帮助!

最佳答案

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

n = chap.length.to_i

太早了。在你把东西放进去之后,你必须得到章节列表的长度。将该行移至此处:

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

puts ('Table of Contents').center lineWidth

而且效果很好。

关于ruby-on-rails - 我可以在 Ruby 中使用循环构建数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18988526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com