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
有帮助吗?

解决方案

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}/)

其他提示

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,"_")}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top