【发布时间】:2014-06-18 15:11:05
【问题描述】:
在这个 Ruby 练习中,我必须访问一个包含三首歌曲的平面文件,其中包含歌曲的标题、艺术家、以分钟和秒为单位的长度以及文件名。该练习要求执行以下操作:
- 将行分成字段,
- 将运行时间从 mm:ss 转换为秒,并
- 删除艺术家姓名中多余的空格。
我继续将以下内容复制并粘贴到纯文本文件中,并将其保存为“songFile”:
/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
: : : :
为了将歌曲行分解为字段,我将其放在终端中:
songs = SongList.new
songFile.each do |line|
file, length, name, title = line.chomp.split(/\s*\|\s*/)
songs.append Song.new(title, name, length)
end
puts songs[1]
然后得到这两条错误信息:
NameError: undefined local variable or method `songFile' for main:Object
NoMethodError: undefined method `[]' for nil:NilClass
【问题讨论】:
-
Rails 并不神奇,您不能只将变量命名为与文件相同的名称,然后让 Rails 知道您打算读取文件。查看
File.open
标签: ruby file nomethoderror nameerror flat