Doodles Doodles - 28 days ago 18
Ruby Question

Write file with line breaks

So I've got a file with the following text:

[[[[[1, 2], [3, 4]], [[1, 2], [3, 4]], [[1, 2], [3, 4]], [[1, 2], [3, 4]], [[1, 2], [3, 4]]]]]


and I need to break the line after every fourth number, so that it looks like this:

[[[[[1, 2], [3, 4]],
[[1, 2], [3, 4]],
[[1, 2], [3, 4]],
[[1, 2], [3, 4]],
[[1, 2], [3, 4]]]]]


I could load the file into a new array, make it to a string, then use:

.delete("[]").delete(" ").split(",").map(&:to_i)


and use:

.each_slice(4) { |a| p a }


to get:

[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]


But I don't know, how to write these lines back to the file, with the line break. I need the file to load into another program, which deletes every bracket, so the output above works fine.

Is there a way to solve it with "\n"?

PS: This is my first post, after founding so much help for my projects on this website.

Answer

Assuming you don't care about the nesting of arrays from input, you could do the following:

arr = [[[[[1, 2], [3, 4]], [[1, 2], [3, 4]], [[1, 2], [3, 4]], [[1, 2], [3, 4]], [[1, 2], [3, 4]]]]]
puts arr.flatten.each_slice(4).map(&:to_s).join("\n")
#=> [1, 2, 3, 4]
    [1, 2, 3, 4]
    [1, 2, 3, 4]
    [1, 2, 3, 4]
    [1, 2, 3, 4]

`

Comments