新手问题 programming-ruby-1-9-2-0 中有一段代码的运行结果不对?

davidlichao · 2013年08月04日 · 最后由 davidlichao 回复于 2013年08月04日 · 2889 次阅读

代码如下:

Song = Struct.new(:title, :name, :length)

File.open("songdata") do |song_file|
    songs = []

    song_file.each do |line|
        file, length, name, title = line.chomp.split(/\s*\|\s*/)
        songs << Song.new(title, name, length)
    end

    puts songs[1]
end

预期结果:

#<struct Song title="Wonderful World", name="Louis Armstrong", length="2:58">

文件 songdata 在同目录下,内容如下:

jazzj00132.mp3   345  Fats     Waller      Ain't Misbehavin'
jazzj00319.mp3   258  Louis    Armstrong   Wonderful World
bgrassbg0732.mp3 409  Strength in Numbers  Texas Red

但是我运行的结果却是:

#<struct Song title=nil, name=nil, length=nil>

请问这是为什么呢?😰

/\s*\|\s*/这个匹配 ' | '

#1 楼 @cantin 意思是正则表达式的问题?请教下怎么得到那个预期结果?

3 楼 已删除

#1 楼 @cantin 哦知道啦,要匹配 ' | '但是待分析的文件里木有 ' | ',真是忧桑。谢谢你!😉

/jazz/j00132.mp3 | 3:45 | Fats Waller | Ain't Misbehavin'
/jazz/j00319.mp3 | 2:58 | Louis Armstrong | Wonderful World
/bgrass/bg0732.mp3| 4:09 | Strength in Numbers | Texas Red
需要 登录 后方可回复, 如果你还没有账号请 注册新账号