我试图在一行上打印几个数组。第一行是好的,但循环在此之后崩溃。我已经尝试了几次,但没有雪茄。这是代码:
chapter_num = ['Chapter 1', 'Chapter 2', 'Chapter 3']
chapter_title = ['Numbers', 'Letters', 'Variables']
chapter_page = ['page 1', 'page 72', 'page 118']
#Prints chapter number
chapter_num.each do |num|
print (num.ljust 0)
#Prints title
chapter_title.each do |title|
print (title.center 14)
#Prints page number
chapter_page.each do |page|
puts (page.rjust 40)
end
end
end
当我运行上面的代码时,它看起来像这样:
Chapter 1 Numbers page 1
page 72
page 118
Letters page 1
page 72
page 118
Variables page 1
page 72
page 118
Chapter 2 Numbers page 1
page 72
page 118
Letters page 1
page 72
page 118
Variables page 1
page 72
page 118
Chapter 3 Numbers page 1
page 72
page 118
Letters page 1
page 72
page 118
Variables page 1
page 72
page 118
它假设看起来像这样:
Chapter 1 Numbers page 1
Chapter 2 Letters page 72
Chapter 3 Variables page 118
答案 0 :(得分:2)
您可以在此处使用Array::zip
方法:
chapter_num = ['Chapter 1', 'Chapter 2', 'Chapter 3']
chapter_title = ['Numbers', 'Letters', 'Variables']
chapter_page = ['page 1', 'page 72', 'page 118']
arr = chapter_num.zip(chapter_title, chapter_page)
arr.each { |el| puts "#{el[0].ljust 0} #{el[1].center 14} #{el[2].rjust 40}" }
#=> Chapter 1 Numbers page 1
#=> Chapter 2 Letters page 72
#=> Chapter 3 Variables page 118
并且 - 由于Array::zip
采用可选块 - 您可以在一行中执行此操作:
chapter_num.zip(chapter_title, chapter_page).each { |el| puts "#{el[0].ljust 0} #{el[1].center 14} #{el[2].rjust 40}" }
答案 1 :(得分:1)
在你的代码中,你有三个嵌套循环,这是获得你得到的输出的原因。您只需要有一个循环来打印每个数组的 i-th 元素,如下所示:
chapter_num = ['Chapter 1', 'Chapter 2', 'Chapter 3']
chapter_title = ['Numbers', 'Letters', 'Variables']
chapter_page = ['page 1', 'page 72', 'page 118']
#Prints chapter number
(0..chapter_num.length-1).each do |i|
puts "#{chapter_num[i].ljust 0} #{chapter_title[i].center 14} #{chapter_page[i].rjust 40}"
end
打印出来:
Chapter 1 Numbers page 1
Chapter 2 Letters page 72
Chapter 3 Variables page 118