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.
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.
The ruby-align CSS property defines the distribution of the different ruby elements over the base.
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.
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.
"Name".ljust(19) "Name".rjust(19)
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With