How to do a newline in output

RubyNewline

Ruby Problem Overview


How do I make \n actually work in my output? At the moment it just writes it all in 1 long block. Thanks for any help

Dir.chdir 'C:/Users/name/Music'
music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
puts 'what would you like to call the playlist?'
@new = ''
playlist_name = gets.chomp + '.m3u'

music.each do |z|
  @new += z + '\n'
end
	
File.open playlist_name, 'w' do |f|
  f.write @new
end

Ruby Solutions


Solution 1 - Ruby

Use "\n" instead of '\n'

Solution 2 - Ruby

You can do this all in the File.open block:

Dir.chdir 'C:/Users/name/Music'
music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
puts 'what would you like to call the playlist?'
playlist_name = gets.chomp + '.m3u'

File.open playlist_name, 'w' do |f|
  music.each do |z|
    f.puts z
  end
end

Solution 3 - Ruby

I would like to share my experience with \n
I came to notice that "\n" works as-

puts "\n\n" // to provide 2 new lines

but not

p "\n\n"

also puts '\n\n'
Doesn't works.

Hope will work for you!!

Solution 4 - Ruby

Actually you don't even need the block:

  Dir.chdir 'C:/Users/name/Music'
  music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
  puts 'what would you like to call the playlist?'
  playlist_name = gets.chomp + '.m3u'

  File.open(playlist_name, 'w').puts(music)

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
QuestionbabyratsView Question on Stackoverflow
Solution 1 - RubykjagielloView Answer on Stackoverflow
Solution 2 - RubyBenView Answer on Stackoverflow
Solution 3 - RubyS.YadavView Answer on Stackoverflow
Solution 4 - RubyTim BreitkreutzView Answer on Stackoverflow