tags:

views:

58

answers:

3

I want to add a whitespace before and after random strings.

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

Thanks

+2  A: 

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 )
BioBuckyBall
Shouldn't that be `pad("random_string")`?
Andrew Grimm
heh, I claim Ruby rust :) fixing it...
BioBuckyBall
+2  A: 
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).

bta
based on the docs, you don't need the second argument to center, but I didn't test, so it could be wrong :)
BioBuckyBall
@Lucas- The second parameter, if present, is a string to use as the padding character(s). If it is omitted, whitespace is used. I think that was an addition in Ruby 1.8, and that link might be referencing version 1.6.
bta
right. I should have stated that you didn't need it to fulfill his request, since based on his question, he wants to append space.
BioBuckyBall
+2  A: 

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

padded_string = ' ' + random_string + ' '
Ed Swangren