开发者

Add whitespace before and after a string in ruby?

I want to add a 开发者_运维问答whitespace before and after random strings.

I have tried using "Random_string".center(1, " ") but it doesnt work.

Thanks


I find this to be the most elegant solution:

padded_string = " #{random_string} "

Nothing wrong with taking the easy way.


irb(main):001:0> x='Random String'
=> "Random String"
irb(main):002:0> y=' '+x+' '
=> " Random String "
irb(main):003:0> x.center(x.length+2)
=> " Random String "

The parameter to center is the total length of the desired output string (including padding).


I mean, is there some reason that you can't just do this?

padded_string = ' ' + random_string + ' '


My ruby is rusty, but IMO nothing wrong with the easy way

def pad( random )
    " " + random + " "
end

padded_random_string = pad("random_string")

using center

"random_string".center( "random_string".length + 2 )


"Random_string".ljust("Random_string".length + 4).rjust("Random_string".length + 8)
or "Random_string".ljust(17).rjust(21) # where "Random_string" is 13 characters long

using .ljust method with .rjust method

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜