2010-01-13 57 views
138

我如何让\n在我的输出中实际工作?目前它只是把它写在1个长块中。感谢您的帮助如何在输出中执行换行

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 

回答

286

使用"\n"而不是'\n'

+8

感谢您的回答,让我看起来像一个傻瓜,但至少我现在知道 – babyrats 2010-01-13 21:18:35

+61

对自己不要太难:唯一的学习方法是提问。 – 2010-01-13 21:58:20

+13

@babyrats - 你不是唯一一个:) – Ninad 2011-09-14 10:57:07

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 
+1

我猜想一个有趣而有用的东西是,'puts'输出一个字符串和一个“自动”拖尾行;这比在代码中添加它更方便。 – 2010-01-13 21:12:45

+0

+1以及用于处理文件的自动关闭惯用方法。 – 2010-01-13 21:13:35

+0

谢谢你。很有帮助。 – babyrats 2010-01-13 21:17:56

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)