ruby - how to pad "groups of 5 characters" with undersores in last group?

485 views Asked by At

I want my string in groups of 5 characters, .e.g.

thisisastring => ["thisi", "satri", "ng"]  

but I also want the last group to be padded with __'s, e.g.

thisisastring => ["thisi", "satri", "ng___"]  

I have got as far as the string splitting:

"thisisastring".scan /.{5}/)

["thisi", "satri", "ng"]

but not too sure how to do the padding for that last group to make it "ng___"

although starting to think that combinations of dividend (div()), modulus (%) and .ljust might do it.

Maybe number of padding characters would be: (length % 5) * "_" (if you can multiply that) ?

Perhaps something that uses:

ruby-1.9.2-p290 :023 > (len % 5).to_i.times { print '_' }
___ => 3
2

There are 2 answers

0
sawa On BEST ANSWER

Since the adjustment is only required on the last element, it is more effective to do the adjustment before splitting rather than itterating over the elements to do adjustment.

("thisisastring"+"_"*("thisisastring".length % 5)).scan(/.{5}/)
3
J. Holmes On

Not even close to efficient, but if you wanted t to one-line it, something like this should work:

"thisisastring".scan(/.{1,5}/).collect {|x| x.ljust(5,"_")}