質問

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