垂直放置一个数组并左对齐

时间:2014-07-28 19:54:26

标签: ruby arrays

这是我以前的一个问题的后续跟进。当我运行这个程序时,数组显示为[" 1"," 2"," 3]等。

这是我的代码:

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

#Needs chapters inputted
chapters = Array.new

puts "Please input chapter names."

while (input = gets.chomp) != ""
  break if input.chomp.empty?
  chapters << input
end

#Needs corresponding page numbers inputted
pagenumbers = Array.new

puts "Please input corresponding page numbers."

while (pagenum = gets.chomp) != ""
  break if pagenum.chomp.empty?
  pagenumbers << pagenum
end

leftside = chapters.to_s
rightside = "Pg. " + pagenumbers.to_s

puts title.center(50)
puts leftside.ljust(30) + rightside.rjust(30)

当我运行它时,它看起来像这样。

MBP-ERDOS:Programs chriserdos$ ruby TOCarray.rb
Please input chapter names.
born 
dead
live

Please input corresponding page numbers.
1
43
99

                Table of Consents                 
["born ", "dead", "live"]              Pg. ["1", "43", "99"]

我希望像这样打印数组:

出生


将相应的页码右对齐在同一行。

Ruby新手,感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

在while循环之后删除所有代码并改为:

data = chapter.zip(pagenumbers)

puts title.center(50)

data.each do |left, right|
  puts left.ljust(30) + right.rjust(30)
end

答案 1 :(得分:0)

您问题的严格答案是:

puts title.center(50)
leftside.each_with_index { |x, i| puts "#{x.ljust(30)}#{rightside[i].rjust(30)}" }

但还有更多方法可以做到这一点。请花些时间做一些Ruby课程或阅读一本书,这是值得的。