我在我正在尝试的Ruby教程中创建了以下代码作为练习的一部分:
title = ['Chapter 1: Numbers','Chapter 2: Letters','Chapter 3: Variables']
pages = ['Page 1','page 72','page 118']
linewidth = 40
header = '*Table of Contents*'
puts header.center linewidth
puts
puts ((title[0]).ljust linewidth/2) + ((pages[0]).rjust linewidth/2)
puts ((title[1]).ljust linewidth/2) + ((pages[1]).rjust linewidth/2)
puts ((title[2]).ljust linewidth/2) + ((pages[2]).rjust linewidth/2)
我的问题是,如果不澄清要显示的数组部分,可以完成上述操作吗?也就是说,我可以在一位代码中按顺序列出所有标题和数组中的所有页面吗?如果是这样,怎么办呢?
答案 0 :(得分:3)
您可以输出如下列表:
titles.each_with_index do |title,index|
puts title.ljust(linewidth/2) + (b[index] ? b[index].rjust(linewidth/2) : nil)
end
答案 1 :(得分:2)
怎么样:
>> title = ['Chapter 1: Numbers','Chapter 2: Letters','Chapter 3: Variables']
#=> ["Chapter 1: Numbers", "Chapter 2: Letters", "Chapter 3: Variables"]
>> pages = ['Page 1','page 72','page 118']
#=> ["Page 1", "page 72", "page 118"]
>>
.. linewidth = 40 #=> 40
>> header = '*Table of Contents*'
#=> "*Table of Contents*"
>> center = linewidth / 2
#=> 20
>> puts header.center linewidth #=> nil
*Table of Contents*
>> puts
#=> nil
>> title.zip(pages) do |t, p|
.. puts "#{t.ljust(center)} #{p.ljust(center)}"
.. end
Chapter 1: Numbers Page 1
Chapter 2: Letters page 72
Chapter 3: Variables page 118
#=> nil
答案 2 :(得分:2)
titles
和pages
是并行数组。 Array.zip
非常适合处理并行数组:
title.zip(pages).each do |title, pages|
puts (title.ljust linewidth / 2) + (pages.rjust linewidth / 2)
end