How do I escape parentheses and brackets in Ruby?
I am trying to escape parentheses and brackets in a short Ruby script. The script takes the name of the directory as an argument, makes a playlist of the .mp3s in the directory, and names the playlist from the directory.
If the directory has braces or pa开发者_StackOverflow中文版rentheses, it fails without an error, it just doesnt make the playlist. Here is the code:
1 #!/usr/bin/ruby -w
2
3 # create a playlist for a specified directory of .mp3 files
4
5 puts "enter path to album:"
6 chomped = gets.chomp
7 path = File.expand_path("#{chomped}")
8
9 data = "#EXTM3U\n"
10 tracks = Dir["#{path}/*.mp3"]
11 name = path.sub(/.*\/(.*)/,"\\1")
12 name.gsub!(/_/," ")
13 name.gsub!(/(\A|\s)\w/) { |c| c.upcase }
14 tracks.sort.each do |track|
15 track_name = track.sub(/.*\/(.*)/,"\\1")
16 data += "#EXTINF:\n" + track_name + "\n"
17 end
18 File.open("#{path}/#{name}.m3u","a") { |f| f.write data }
19 puts "created #{path}/#{name}.m3u"
I have been able to escape the underscores, and I think I got a regex working to escape the other characters, (http://rubular.com/r/BNUnjSde6J) but it still fails using .gsub!
. Also, I would rather not escape them, I'd like the title to include them. Would Regexp.escape
be an answer?
EDIT: to clarify, the tracknames need not be full paths because the playlist will reside in the same directory as the tracks themselves. see: http://en.wikipedia.org/wiki/M3U
The following should work:
escaped_path = path.gsub(/([\[\]\{\}\*\?\\])/, '\\\\\1')
tracks = Dir["#{escaped_path}/*.mp3"]
I determined the characters that needed to be escaped by looking at the API for Dir.glob. The regular expression is complicated because the same characters are also used in regular expressions!
Separate to your parentheses problem, you have a bigger issue. You're basically re-writing the m3u file over and over like Schlemiel the Painter. Better to open the file handle outside of the track loop instead.
精彩评论