Getting line breaks into formatted output

I’m kind of embarrassed to even ask this, but I can’t find an elegant
solution. If I have an large array that I want to print across several
lines, how do I do it. I naively thought I could just use sprintf, but
shockingly it has no idea how to handle a line break with \n.

Example, if I have 43 element array, and I want to print it in formatted
blocks of 13 on subsequent lines:

x[0] x[1] … x[13]
x[14] x[14] … x[26]
x[27] x[26] … x[39]
x[40] x[41] x[42] x[43]

I can do it, but it takes lengthy, highly explicit coding which makes my
stomach turn over in disgust…

A solution may be to split up your 43 element Array into a sub-slice of
that.

your_array.each_slice(number_here).to_a
your_array.each_slice(13).to_a

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs