如何在输出中换行

时间:2010-01-13 21:04:07

标签: ruby newline

如何让\n在我的输出中真正起作用?目前它只是在一个长块中写入它。谢谢你的帮助

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

4 个答案:

答案 0 :(得分:315)

使用"\n"代替'\n'

答案 1 :(得分:12)

您可以在File.open块中完成所有操作:

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

答案 2 :(得分:5)

实际上你甚至不需要这个块:

  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)

答案 3 :(得分:0)

我想与\n分享我的经验
我注意到“ \ n”的工作方式为-

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

但不是

p "\n\n"

也 放置'\n\n'
不起作用。

希望会为您服务!