I have few ruby strings, which I want to align left and right appropriately.
我有几个ruby字符串,我想左右对齐。
I'm now using "Name".center(20, " ")
to get "(7 spaces)Name(8 spaces)"
我现在正在使用“名称”.center(20,“”)来获取“(7个空格)名称(8个空格)”
How can I achieve "Name(15 spaces)"
or "(15 spaces)Name"
如何实现“名称(15个空格)”或“(15个空格)名称”
Thanks.
谢谢。
3 个解决方案
#1
33
"Name".ljust(19)
"Name".rjust(19)
#2
4
Ruby has a printf
method defined in Kernel
, try using that.
Ruby有一个在Kernel中定义的printf方法,尝试使用它。
It supports many common "f
" ("format", like in scanf
, printf
, ...) options (see e.g. man 3 printf
).
它支持许多常见的“f”(“格式”,如scanf,printf,...)选项(参见例如man 3 printf)。
Left and right justification can be done like this (extracted from comment):
左右对齐可以这样做(从评论中提取):
printf("%10s", "right")
printf("%-10s","left")
#3
1
Insert n Copies of a Character
There are certainly other ways to do this, but one of them is to use the splat operator to copy a character (e.g. the space character) a certain number of times. For example:
当然还有其他方法可以做到这一点,但其中一种方法是使用splat运算符将字符(例如空格字符)复制一定次数。例如:
puts (' ' * 15) + 'Name'
puts 'Name' + (' ' * 15)
#1
33
"Name".ljust(19)
"Name".rjust(19)
#2
4
Ruby has a printf
method defined in Kernel
, try using that.
Ruby有一个在Kernel中定义的printf方法,尝试使用它。
It supports many common "f
" ("format", like in scanf
, printf
, ...) options (see e.g. man 3 printf
).
它支持许多常见的“f”(“格式”,如scanf,printf,...)选项(参见例如man 3 printf)。
Left and right justification can be done like this (extracted from comment):
左右对齐可以这样做(从评论中提取):
printf("%10s", "right")
printf("%-10s","left")
#3
1
Insert n Copies of a Character
There are certainly other ways to do this, but one of them is to use the splat operator to copy a character (e.g. the space character) a certain number of times. For example:
当然还有其他方法可以做到这一点,但其中一种方法是使用splat运算符将字符(例如空格字符)复制一定次数。例如:
puts (' ' * 15) + 'Name'
puts 'Name' + (' ' * 15)