如何使用gets.chomp填充数组

时间:2014-07-27 02:24:22

标签: ruby arrays

这是我到目前为止所拥有的:

#Table of Contents using an array
title = "Table of Consents"

#Needs chapters inputted
chapters = Array.new

puts "Please input chapter names."

while gets.chomp != ""
  chapter = gets.chomp
  chapters.push chapter
  break if gets.chomp.empty?
end

#Needs corresponding page numbers inputted
pagenumbers = Array.new

puts "Please input corresponding page numbers."

while gets.chomp != ""
  pagenum = gets.chomp
  pagenumbers.push pagenum
  break if gets.chomp.empty?        
end

puts chapters
puts page numbers

我试图让gets.chomp继续添加到每个阵列。当我按chapterpagenum时,我只获得最后一个字符串/整数输入。如何让每个输入填充chapterpagenum数组?

1 个答案:

答案 0 :(得分:0)

这里的问题是,每次在程序中编写gets时,都会调用gets方法,该方法从用户处获取一行输入。您需要将该行存储在某处,以便以后使用。尝试这样的事情:

chapters = []
while true
  input = gets.chomp
  break if input.empty?
  chapters << input
end
puts "Chapters: " + chapters.join(", ")