Add spaces before and after line in ruby?

I want to add spaces before and after random lines.

I tried using "Random_string" .center (1, ""), but it does not work.

thanks

+4
source share
5 answers

My ruby ​​is rusty but imo nothing wrong with an easy way

def pad( random ) " " + random + " " end padded_random_string = pad("random_string") 

using the center

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

I consider this the most elegant solution:

padded_string = " #{random_string} "

Nothing wrong with making the easy way.

+5
source

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

 padded_string = ' ' + random_string + ' ' 
+4
source
 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 center parameter is the total length of the required output line (including padding).

+3
source

"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. simple method with the .rjust method

+1
source

All Articles