在ruby上匹配并删除一些标题字符串

时间:2012-05-27 09:01:57

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

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

要解析的文件看起来像这样。

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

我想删除

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

这一部分。

编辑:我写了一个像这样的红宝石代码

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

但是,我觉得我的代码很脏,应该清理。 如何简化代码?

1 个答案:

答案 0 :(得分:0)

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

这样的事情:

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