Table of contents

I’m supposed to layout table of contents but have my contents stored in
an array first. I decided to represent my contents with the letter “c”,
and hence naming each content as shown below

title = “Table of Contents”

c1a = “Chapter 1:”
c1b = “Getting Started”
c1c = “page 1”

c2a = “Chapter 2:”
c2b = “Numbers”
c2c = “page 9”

c3a = “Chapter 3:”
c3b = “Letters”
c3c = “page 13”

line_width = 40
page_column=10
toc = [title, c1a, c1b, c1c, c2a, c2b, c2c, c3a, c3b, c3c]

puts (toc[0].center (line_width))
puts (toc[1,2].join(" “).ljust (line_width)) + (toc[3].rjust
(page_column))
puts (toc[4,5].join(” “).ljust (line_width)) + (toc[6].rjust
(page_column))
puts (toc[7,8].join(” ").ljust (line_width)) + (toc[9].rjust
(page_column))

I expected to see something like

               Table of Contents

Chapter 1: Getting Started page 1
Chapter 2: Numbers page 9
Chapter 3: Letters page 13

When I execute this code, I get a weird arrangement without error
messages but isn’t what I expect to see… I also don’t seem to figure
out my mistake. Someone should please help me find my bearings :slight_smile: thanks

Note: The code doesn’t break to a new line at the “(page_column))”, its
on the same line as the puts line above it, the editor won’t allow me to
type that many characters on one line here :confused:

2011/10/14 Samuel M. [email protected]:

puts (toc[1,2].join(" “).ljust (line_width)) + (toc[3].rjust
(page_column))
puts (toc[4,5].join(” “).ljust (line_width)) + (toc[6].rjust
(page_column))
puts (toc[7,8].join(” ").ljust (line_width)) + (toc[9].rjust
(page_column))

You are confusing two array access method in the last three lines.

arr[a, b] (with a comma - two arguments) means “b elements, starting
from index a”.

arr[a…b] (with two dots - a range) means “elements, starting from
index a, ending at index b, inclusive” (with three commas, it’d be
“…exclusive”).

Refer to the docs for details.

– Matma R.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs