Text formatting

Hello people!
I am very new to Ruby. Yesterday I bought very nice book about Ruby and
immediately started learning. Now I have little problem :slight_smile:
The exercise is to display text like this:

            Table of Contents

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

but my text always looks like this:

            Table of Contents

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

My code is:

line_width = 50
str1 = ‘Table of Contents’
str_chap1 = ‘Chapter 1: Getting Started’
str_chap2 = ‘Chapter 2: Numbers’
str_chap3 = ‘Chapter 3: Letters’

str_page1 = ‘page 1’
str_page9 = ‘page 9’
str_page13 = ‘page 13’

puts(str1.center(line_width))
puts’’
puts(str_chap1.ljust(line_width/2) + str_page1.rjust(line_width/2))
puts(str_chap2.ljust(line_width/2) + str_page9.rjust(line_width/2))
puts(str_chap3.ljust(line_width/2) + str_page13.rjust(line_width/2))

What should I do to vertically align strings )‘page 1’, ‘page 9’ and
‘page 13’)?

P.S. If you know some more better way to write this, I would be happy to
see it (and to try to understand it :slight_smile: )
P.S. Sory if this is a stuped question.

Dear “Keep Going”,

puts str_chap1.ljust(line_width) + str_page1
puts str_chap2.ljust(line_width) + str_page9
puts str_chap3.ljust(line_width) + str_page13

But the total line_width will be line_width (50) + str_page.size.

If you want all the line to fit in the 50 chars you just need to
subtract that value.

The longer line is str_page13 = ‘page 13’ and is 7.
So,

puts(str_chap1.ljust(line_width-7) + str_page1)
puts(str_chap2.ljust(line_width-7) + str_page9)
puts(str_chap3.ljust(line_width-7) + str_page13)

Best regards,
Abinoam Jr.

Hehe, so simple and logical but I would never think about that :slight_smile:
Thank you dear Abinoam Jr. :slight_smile:

You’re welcome!

But… Abinoam in not a nick… is my real name :slight_smile:

Abinoam Jr.

PS: Posting from ruby-forum you are showing up as “Keep Going” :slight_smile:
So, “Keep Going” keep going and you will do it well!

Hmmm, I see almost everybody are using real names here so…
Done & done!
Now, I am using my real name :slight_smile:

quote:
So, “Keep Going” keep going and you will do it well!

Thank you :slight_smile:

Correcting…

Vladimir Magoc, keep going and you will do it well!!! :wink:

Best regards,
Abinoam Jr.

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