0

好的,我尝试从文件中删除包含 -- 的行。该文件如下所示:

  -----------------------------------------------------------------
  Lorem ipsum....
  Text.....

我的代码:

  f = File.open('C:\websites\ahr.txt')
  f.each_line do |line|
    if line.include? '-'
     a = line
     line.delete a
    end
  end
f = File.close

但它不会工作!我收到此错误:

 file.rb:5:in `delete': invalid range "-- (ArgumentError)
 " in string transliteration
    from file.rb:5:in `block in <main>'
    from file.rb:2:in `each_line'
    from file.rb:2:in `<main>'

这是怎么回事?

4

2 回答 2

2

发生什么了?

像这样的东西:

line = "-----------------------------------\n"
 => "-----------------------------------\n"

a = line
 => "-----------------------------------\n"

line.delete a
 ArgumentError: invalid range "--
 " in string transliteration

delete方法引发的错误是因为破折号用于特殊字符范围语法:

"hellob".delete "a-e"
 => "hllo"

可能您想采用不同的方法来解决您的目标,但是很难说出您想要什么,因为一旦删除了行,您就不会显示您想要对数据做什么。简单地处理line变量只是意味着你String在那个时候已经改变了。

于 2013-07-25T10:12:46.027 回答
1

As others said, you can do it with grep, but if you want to do it completely in Ruby, then look at this question, the first answer should help you.

于 2013-07-25T10:13:45.497 回答