在 Ruby(1.9.2)中,我有两个来自两个不同来源(二进制数据)的长数字流。
这两个源以两个Enumerators的形式封装。
我想检查两个流是否完全相等。
我提出了几个解决方案,但两者似乎都很不雅。
第一个只是将两者都转换为数组:
def equal_streams?(s1, s2)
s1.to_a == s2.to_a
end
这行得通,但在内存方面,它的性能不是很好,特别是在流有很多信息的情况下。
另一种选择是……呃。
def equal_streams?(s1, s2)
s1.each do |e1|
begin
e2 = s2.next
return false unless e1 == e2 # Different element found
rescue StopIteration
return false # s2 has run out of items before s1
end
end
begin
s2.next
rescue StopIteration
# s1 and s2 have run out of elements at the same time; they are equal
return true
end
return false
end
那么,有没有更简单、更优雅的方法呢?