我正在尝试在Ruby中实现类似尾部的程序。但是,我的tail方法返回一个数组作为行数(有限,即本例中为10,这意味着数组大小始终为10),它读取。
所以,我第一次保存了我读过的所有日志文件的最后10行。这看起来像这样:
["\n", "Some Data\n", "\n", "One Value here\n", "\n", "sure sure\n", "\n", "Random thoughts\n", "\n", "Wait!!\n"]
一个我修改日志文件,追加一些带有新数据的新行。我的尾巴返回一个新的数组(具有相同的有限大小,即10)。这看起来像这样:
["\n", "sure sure\n", "\n", "Random thoughts\n", "\n", "Wait!!\n", "\n", "Error - nothing found\n", "\n", "go to sleep\n"]
因此,如果您注意到第二个数组显示了进度。请参见第一个数组的索引5处的值现在位于第二个数组的索引1处。因此,这显然可以选择显示第二个数组的"Wait!!\n"
条目后发生的所有内容或更改。现在,我正面临着避免重复/重复值的问题。
所以,如果我拿第一个数组:ar1
和第二个数组:ar2
并执行:ar2 - ar1
,则会显示:
["Error - nothing found\n", "go to sleep\n"]
哪个不正确,理想情况应该如此:
["\n", "Error - nothing found\n", "\n", "go to sleep\n"]
基本上,无论是在最后一行之后发生了什么。我只需要更改的行,并且只想删除先前tail
输出中出现的那些重复项。反正有吗?
答案 0 :(得分:1)
ary1 = ["\n", "Some Data\n", "\n", "One Value here\n", "\n", "sure sure\n", "\n", "Random thoughts\n", "\n", "Wait!!\n"];
ary2 = ["\n", "sure sure\n", "\n", "Random thoughts\n", "\n", "Wait!!\n", "\n", "Error - nothing found\n", "\n", "go to sleep\n"];
ary2[(ary2.index(ary1.last) + 1)..(ary2.size - 1)]
=> ["\n", "Error - nothing found\n", "\n", "go to sleep\n"]
答案 1 :(得分:0)
我建议使用类似File::Tail
的库来实现Ruby中的尾部行为,而不是重新发明轮子并尝试对数组进行复杂的启发式重复数据删除。
答案 2 :(得分:0)
您实际上不想删除重复项,您只想显示这些内容 你还没有表现出来。
取ar1中最后一项的值,在ar2中找到该项的索引,打印 ar2的尾巴。 (代码大纲没有错误处理)
shown = ar1.last
show = ar2.index(shown)
print ar2[show..-1]
然而,实际上并未涵盖所有可能的情况。问题是数组与底层数据结构的匹配非常差。