Add a new line in file?

Ruby

Ruby Problem Overview


I want to add a new line after a string is inserted.

My current code looks like this:

  File.open(filename, 'a') do |file|
    file.write @string
  end

How could I add a new line after the string is inserted?

Ruby Solutions


Solution 1 - Ruby

Use IO#puts.

file.puts @string

Solution 2 - Ruby

file.write "\n"

Solution 3 - Ruby

In case if you can't use IO#puts:

file.write "text#{$/}"

where $/ represents OS-dependent new line separator.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionnever_had_a_nameView Question on Stackoverflow
Solution 1 - RubymaletorView Answer on Stackoverflow
Solution 2 - RubyBorealidView Answer on Stackoverflow
Solution 3 - RubylazyleadView Answer on Stackoverflow