使用在文件中多次出现的标记来分割线条
我有一个文件,其内容如下:
this is test line 1 this is testing purpose am inside of public doing lot of stuffs and priting result here am inside of another public doing another set of stuffs and priting here
我想将此文件拆分为三个不同的部分:
- 不属于任何部分的线条
- 第一部分内部的线条
- 第二部分内部的线条
我尝试了take_while
和drop_while
,
File.open(filename).each_line.take_while do |l| !l.include?('') end.drop_while do |l| !l.include?('') end.drop(1))
但它只提取第一个 …
部分。
我正在寻找更好的解决方案。 任何建议将不胜感激。
File.read(filename).split(/<\/?public>/) .map(&:strip) .reject(&:empty?) # [0..2] if the file has a tail #⇒ [ # [0] "this is test line 1 \nthis is testing purpose", # [1] "am inside of public\ndoing lot of stuffs and priting result here", # [2] "am inside of another public\ndoing another set of stuffs and priting here" # ]