我有两个来自不同来源(二进制数据)的长数字流,使用Ruby(1.9.2)。
这两个源被封装在两个枚举器的形式中。
我想检查这两个流是否完全相等。
我想到了几种解决方案,但都似乎不太优雅。
第一种方法只是将它们转换为数组:
那么,有没有更简单、更优雅的方法来完成这个任务呢?
这两个源被封装在两个枚举器的形式中。
我想检查这两个流是否完全相等。
我想到了几种解决方案,但都似乎不太优雅。
第一种方法只是将它们转换为数组:
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
那么,有没有更简单、更优雅的方法来完成这个任务呢?
zip
的问题在于它会在内部创建数组,无论你传递什么 Enumerable。还有一个问题是输入参数的长度。 - Mladen Jablanović1.times.zip(1.times) {|x,y| puts x, y; 42}
输出 0,0 并返回nil
。 - Andrew Grimm