2

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
Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
  • 2
    Not a Ruby expert, but why not just check the last element in the array for its length. Append 5-length '_'s to it? –  Feb 02 '12 at 21:37

2 Answers2

6

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,"_")}
J. Holmes
  • 18,466
  • 5
  • 47
  • 52
4

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}/)
sawa
  • 165,429
  • 45
  • 277
  • 381