25 Apr 2008, 18:28
Cheese-grater-sm_pragsmall

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

30 Jun 2008, 08:15
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])
24 Aug 2008, 21:17
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
`
15 Jul 2012, 21:17
Generic-user-small

Cory McDowell (1 post)

I also had a similar problem. With my current code, I have a page title array and a page number array, but I don’t know how to get them on the same line. Some help would be greatly appreciated, thanks.

Table of Contents

contents = [] number = []

puts ‘Enter the Page title: ‘
title = gets.chomp
page = 1

while title != ‘’
contents.push title
number.push page
title = gets.chomp
page = page + 1
end

line_width = 50

contents.each do |page|
puts (page.ljust(line_width/2))
end

number.each do |num|
puts (num.to_s.rjust(line_width/2))
end

  You must be logged in to comment