Ruby 如何从字符串中删除转义字符?UTF问题?

Ruby 如何从字符串中删除转义字符?UTF问题?,ruby,xml,utf-8,escaping,Ruby,Xml,Utf 8,Escaping,我读入了一个XML文件,其中包含如下行 <Song name="Caught Up In You" id='162' duration='276610'/> 我正在和你一起读文件 f=File.open(file) f.each_with_index do |line,index| if line.match('Song name="') @songs << line puts line if (index % 1000) == 0 end

我读入了一个XML文件,其中包含如下行

 <Song name="Caught Up In You" id='162' duration='276610'/>

我正在和你一起读文件

f=File.open(file)
f.each_with_index do |line,index|
  if line.match('Song name="')
    @songs << line
    puts line if (index % 1000) == 0
  end
end
f=File.open(文件)
f、 每个带索引的|行,索引|
if line.match('Song name=“”)

@歌曲您的文本没有“转义”字符。字符串的
.inspect
版本会显示这些字符。请注意:

> s = gets
Hello "Michael"
#=> "Hello \"Michael\"\n" 

> puts s
Hello "Michael"

> p s  # The same as `puts s.inspect`
"Hello \"Michael\"\n"
但是,真正的答案是将此XML文件作为XML处理。例如:

require 'nokogiri'                                # gem install nokogiri
doc = Nokogiri.XML( IO.read( 'mysonglist.xml' ) ) # Read and parse the XML file
songs = doc.css( 'Song' )                         # Gives you a NodeList of song els
puts songs.map{ |s| s['name'] }                   # Print the name of all songs
puts songs.map{ |s| s['duration'] }               # Print the durations (as strings)

mins_and_seconds = songs.map{ |s| (s['duration'].to_i/1000.0).divmod(60) }
#=> [ [ 4, 36.6 ], … ]

很公平。称它们为“编码”。如何删除它们?@michaelcurrent检查字符串时,带有双引号的字符串显示为
\”
,但其中只有一个双引号。带有换行符的字符串只有一个换行符(可以使用
.strip
从末尾删除),但显示为
\n
。你真的想用iTunes音乐商店做什么?只是玩代码。它实际上是一个包含5000首歌曲的示例音乐文件。我不知道是itunes格式:)是解析和管理XML的一个令人愉快的库。
require 'nokogiri'                                # gem install nokogiri
doc = Nokogiri.XML( IO.read( 'mysonglist.xml' ) ) # Read and parse the XML file
songs = doc.css( 'Song' )                         # Gives you a NodeList of song els
puts songs.map{ |s| s['name'] }                   # Print the name of all songs
puts songs.map{ |s| s['duration'] }               # Print the durations (as strings)

mins_and_seconds = songs.map{ |s| (s['duration'].to_i/1000.0).divmod(60) }
#=> [ [ 4, 36.6 ], … ]