rjust alignment

R

Ross

I think I'm going crazy. I tried to write a fairly simple program to
test ljust, center and rjust. But I cannot make the page numbers of my
table of contents line up. I tried to account for the string length of
the chapter and topics; I've tried a lot of things and I just cannot get
the page numbers to line up. If anyone knows how to do it please let me
know. I don't think I'll be able to go to bed without figuring it out.
Here is my latest code and output:

////////// code //////////////

class TableOfContents
attr_accessor :chapters, :topics, :pages
end

toc = TableOfContents.new
toc.chapters = ["Chapter 1", "Chapter 2", "Chapter 3"]
toc.topics = ["Numbers", "Letters", "Variables"]
toc.pages = ["Page 1", "Page 57", "Page 117"]

lineWidth = 20
3.times do |x|
offset = toc.chapters[x] + ": " + toc.topics[x]
offset = 40 - offset.length
puts toc.chapters[x] + ": " + toc.topics[x] +
toc.pages[x].rjust(lineWidth + offset + (10 - toc.pages[x].length))
end

//////////// output /////////////////

Chapter 1: Numbers Page 1
Chapter 2: Letters Page 57
Chapter 3: Variables Page 117

!! Using this line rather than the above line 14 gives this

new line 14:

puts toc.chapters[x] + ": " + toc.topics[x] +
toc.pages[x].rjust(lineWidth)

new output:

Chapter 1: Numbers Page 1
Chapter 2: Letters Page 57
Chapter 3: Variables Page 117

Thanks
 
R

Ross Nicol

Thanks. I am using FreeRIDE and the output shows up differently, but if
I copy and paste the output to a text file it is lined up like it is
supposed to be.

Thanks for the suggestions.
 
J

John Joyce

Maybe you're looking at the numbers wrong.
You could roll your own pretty easily.
Some pseudo code:

TotalWidth = x
TotalWidthForLine = TotalWidth - ( ChapterTitleWidth + PageNumberWidth )
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,276
Latest member
Sawatmakal

Latest Threads

Top