【问题标题】:Match and delete some header strings on ruby匹配并删除 ruby​​ 上的一些标题字符串
【发布时间】:2012-05-27 09:01:57
【问题描述】:

我想解析文件并删除 ruby​​ 上的一些标头字符串。

要解析的文件如下所示。

---
some
text
text2
string
and
so
on
---
another string
and the other

我想删除

---
some
text
text2
string
and
so
on
---

这部分。

编辑:我写了一个这样的 ruby​​ 代码

file = File.open("test")
a = file.readlines
skip = 0
a.each do |line|
   if line.match("---\n")
     if skip == 1
       skip-=1
     else
       skip+=1
     end
   else
     if skip != 1
       print line 
     end
   end

end

这可行,但是,我认为我的代码很脏,应该清理。 如何简化我的代码?

【问题讨论】:

    标签: ruby coding-style header rubygems pattern-matching


    【解决方案1】:

    这是一项微不足道的任务(假设文件格式正确)。

    类似这样的:

    lines = # read lines from file
    
    is_header_mode = false
    lines.each do |line|
       if line == '---'
         is_header_mode = !is_header_mode
       else
         puts line unless is_header_mode
       end
    end
    

    【讨论】:

    • 谢谢!我添加了我的 ruby​​ 代码,你能给我一些建议吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-04
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多