Doodles
Doodles

Reputation: 15

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.

Upvotes: 0

Views: 619

Answers (3)

Oleksandr Holubenko
Oleksandr Holubenko

Reputation: 4440

Another way is:

arr = [[[[[1, 2], [3, 4]], [[1, 2], [3, 4]], [[1, 2], [3, 4]], [[1, 2], [3, 4]], [[1, 2], [3, 4]]]]]

> arr.flatten(2).each { |string| p sting.flatten }
# => [1, 2, 3, 4]
# [1, 2, 3, 4]
# [1, 2, 3, 4]
# [1, 2, 3, 4]
# [1, 2, 3, 4]

Upvotes: 0

7stud
7stud

Reputation: 48599

data = [
  '[1, 2]',
  '[1, 2]',
  '[1, 2]',
]

File.open('output.txt', 'w') do |f|
  data.each do |string| 
    f.puts string
  end
end

$ cat output.txt
[1, 2]
[1, 2]
[1, 2]

Upvotes: 0

Wand Maker
Wand Maker

Reputation: 18762

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]

`

Upvotes: 1

Related Questions