我有一个文件,其内容如下:
this is test line 1
this is testing purpose
<public>
am inside of public
doing lot of stuffs and priting result here
</public>
<public>
am inside of another public
doing another set of stuffs and priting here
</public>
我想将此文件拆分为三个不同的部分:
我尝试使用take_while
和drop_while
,
File.open(filename).each_line.take_while do |l|
!l.include?('</public>')
end.drop_while do |l|
!l.include?('<public>')
end.drop(1))
但它仅提取第一个<public>
... </public>
部分。
我正在寻找更好的解决方案。任何建议都将不胜感激。
答案 0 :(得分:2)
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"
# ]