Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align ruby string to left or right?

Tags:

I have few ruby strings, which I want to align left and right appropriately.

I'm now using "Name".center(20, " ") to get "(7 spaces)Name(8 spaces)"

How can I achieve "Name(15 spaces)" or "(15 spaces)Name"

Thanks.

like image 582
Sathish Manohar Avatar asked Feb 22 '13 09:02

Sathish Manohar


People also ask

How do I center a string in Ruby?

We can use the center() method to center a string in Ruby. The center() method centers a string in the specified width. If the specified width is greater than the string, center() returns a new string with a length equal to the width.

What is Ruby align in CSS?

The ruby-align CSS property defines the distribution of the different ruby elements over the base.

What is Rjust in Ruby?

Overview. We can right justify a string in Ruby by using the rjust() method. The rjust method requires a mandatory parameter, an integer, which gives the number of spaces to use to justify the string, and an optional pad string.

How do you print a string in Ruby?

To display a string in your program, you can use the print method: print "Let's print out this string." The print method displays the string exactly as written. print 'This is the first string.


2 Answers

"Name".ljust(19) "Name".rjust(19) 
like image 68
sawa Avatar answered Sep 17 '22 13:09

sawa


Ruby has a printf method defined in Kernel, try using that.

It supports many common "f" ("format", like in scanf, printf, ...) options (see e.g. man 3 printf).

Left and right justification can be done like this (extracted from comment):

printf("%10s", "right") printf("%-10s","left")  
like image 25
s.m. Avatar answered Sep 18 '22 13:09

s.m.