Jack Kelly Jack Kelly - 1 month ago 6
Ruby Question

How do I use ljust and rjust correctly in ruby?

So right now I have some code:

line_width = 26

ch3 = "Chapter 3: Letters page 13"
puts(ch3.ljust(line_width/2) + ch3.rjust(line_width/2))

#=> Chapter 3: Letters page 13Chapter 3: Letters page 13


I would like the output to be split down the middle. Like this:

Half-Text__________________________________________________Half-Text

How do I do this?

Answer

You need to split the text into two first.

line_width = 26

ch3 = "Chapter 3: Letters page 13"

ch3 = ch3.split(/\s(?=page)/) #=> ["Chapter 3: Letters", "page 13"]

puts(ch3[0].ljust(line_width / 2) + ch3[1].rjust(line_width / 2))

This outputs

Chapter 3: Letters      page 13
Comments