【问题标题】:How to access and manipulate a flat file?如何访问和操作平面文件?
【发布时间】: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


【解决方案1】:

打开文件并执行操作。像这样的

...
File.open("songFile") do |sf|
  sf.each do |line|
  ...
  end
end
...

【讨论】:

    【解决方案2】:

    假设您有文本文件与脚本位于同一目录中那么

    songs = SongList.new
    
    File.readlines('./songFile').each do |song|
      file, length, name, title = line.chomp.split(/\s*\|\s*/)
      songs.append Song.new(title, name, length)
    end
    
    puts songs[1]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多