Cheese-grater-sm_small Matt Rutledge 1 post

Hi!
Im new to programming (and Ruby of course) and am working through Chris Pine’s tutorial as a starting point. At the end of chapter 7 there is a ‘A Few Things to Try’ project where you rewrite the Table of Contents program to utilize arrays. Id like to house the information (ie Chapter Title and Page) in two seperate arrays and then cycle through code for each string in each array at the same time (hopefully this makes sense..).

Here is the code that Ive come up with (but of course doesnt work):


page_width = 50

contents = ['Chapter 1: Getting Started','Chapter 2: Numbers','Chapter 3: Letters']
pages = ['1','9','13']

contents.each do |content| and pages.each do |page|
puts(content.ljust(page_width/2)) + (page.rjust(page_width/2))
end

Im confident that Im going about this the wrong way…any hints?

THANKS

 
Generic-user-small Jeff Townsend 2 posts

I’m not sure if this is even close to what the author had in mind, but it worked for me:


line_width = 40

table_of_contents = ["1. Intro".ljust(line_width/2), "2. Middle".ljust(line_width/2), "3. End".ljust(line_width/2), "Page 1".rjust(line_width/2), "Page 5".rjust(line_width/2), "Page 10".rjust(line_width/2), "Table of Contents".center(line_width)]

puts(table_of_contents[6])
puts(table_of_contents[0] + table_of_contents[3])
puts(table_of_contents[1] + table_of_contents[4])
puts(table_of_contents[2] + table_of_contents[5])

 
Generic-user-small Domingo Valls 1 post

How about this, with a 2-dimensional array:


lineWidth = 60
toc = [ [1, "Numbers", 1], [2, "Letters", 72], [3, "Variables", 118] ]
puts 'Table of Contents'.center(lineWidth)
puts ''
toc.each do |line|
  izquierda = 'Chapter ' + line[0].to_s + ': ' + line[1]
  derecha = 'page ' + line[2].to_s
  puts izquierda.ljust(lineWidth/2) + derecha.rjust(lineWidth/2)
end

    

3 posts, 3 voices