我正在编写一个简单的脚本来搜索TODO:和FIXME的文档:并返回匹配和行号。我有一个(非常糟糕的)版本工作,我现在想知道如何正确地做到这一点。
我需要转过身来:
todo: alpha
bravo
fixme: charlie
fixme: delta
echo
frank
todo: golf
进入这个:
1 - todo: alpha
7 - todo: golf
3 - fixme: charlie
4 - fixme: delta
请注意,编号结果按标记排序。
答案 0 :(得分:0)
这是一种方式:
doc = <<DOC
todo: alpha
bravo
fixme: charlie
fixme: delta
echo
frank
todo: golf
DOC
doc.split("\n").map.with_index {|s,i| [i,s]}.select {|(i,s)| s.include?("todo:")|| \
s.include?("fixme:")}.sort_by(&:last).map {|(i, s)| "#{i+1} - " + s}
=> ["3 - fixme: charlie",
"4 - fixme: delta",
"1 - todo: alpha",
"7 - todo: golf"]
按步骤:
s1 = doc.split("\n").map.with_index {|s,i| [i,s]}
=> [[0, "todo: alpha"], [1, "bravo"], [2, "fixme: charlie"],
[3, "fixme: delta"], [4, "echo"], [5, "frank"], [6, "todo: golf"]]
s2 = s1.select {|(i,s)| s.include?("todo:") || s.include?("fixme:")}
=> [[0, "todo: alpha"], [2, "fixme: charlie"],
[3, "fixme: delta"], [6, "todo: golf"]]
s3 = s2.sort_by(&:last) # Equivalent to s2.sort_by {|a| a.last}
=> [[2, "fixme: charlie"], [3, "fixme: delta"],
[0, "todo: alpha"], [6, "todo: golf"]]
s3.map {|(i, s)| "#{i+1} - " + s}
=> ["3 - fixme: charlie", "4 - fixme: delta",
"1 - todo: alpha", "7 - todo: golf"]