Ruby拆分字符串块2级错误

时间:2014-02-24 11:43:11

标签: ruby

我想从文本文件中提取所有文件名

文件temp.txt

Expand or Collapse
Add App To Favorites - Ajax;Plugin;AjaxOnSmallDevicesReveal_lmstat_1111.qvwDefault1899-12-30 05:30



Expand or Collapse
Add App To Favorites - Ajax;Plugin;AjaxOnSmallDevicesReveal_lmstat_140109_v2_reduced.qvwDefault2014-01-10 15:56



Expand or Collapse
Add App To Favorites - Ajax;Plugin;AjaxOnSmallDevicesReveal_lmstat_ONLYPV.qvwDefault2014-02-07 18:34

我正在使用以下代码

file = File.open("temp.txt", "r")
   while (line = file.gets)     
       if line.text.include? "Devices"
           string=line.split("Devices")[1]
           File.open("out.txt", 'a') {|f| f.puts string.split(".qvw")[0] + ".qvw" }
           end
   end
file.close

但不知何故,我最终得到了分裂函数的以下错误。

1) Error:
test_script(M_Dev_Script):
NoMethodError: undefined method `split' for nil:NilClass
M_Test_Script.rb:65:in `block (2 levels) in file2'
M_Test_Script.rb:65:in `open'

根据错误消息,我能够知道错误发生在

  

string.split( “qvw”)[0]

但我无法找到错误的正确解决方案,请帮忙吗?

1 个答案:

答案 0 :(得分:1)

从原始代码中,我在undefined method 'text'表达式上获得line.text.include?line已经是字符串,您无需选择text

试试这个:

open("temp.txt", "r").each do |line|
  if line.include? "Devices"
    string=line.split("Devices")[1]
    open("out.txt", 'a') {|f| f.puts string.split(".qvw")[0] + ".qvw" }
  end
end

或者更简单:

open("out.txt", "a") do |f|
  open("temp.txt", "r").each do |line|
    f.puts line.split("Devices")[1].split(".qvw")[0] + ".qvw" if line.include? "Devices"
  end
end

收率:

$ cat out.txt
Reveal_lmstat_1111.qvw
Reveal_lmstat_140109_v2_reduced.qvw
Reveal_lmstat_ONLYPV.qvw