Ruby - 优雅地比较两个枚举器 [英] Ruby - Compare two Enumerators elegantly
问题描述
我在 Ruby (1.9.2) 中有两个来自两个不同来源(二进制数据)的长数字流.
I've got two long streams of numbers coming from two different sources (binary data) in Ruby (1.9.2).
这两个源被封装成两个Enumerators的形式.
The two sources are encapsulated in the form of two Enumerators.
我想检查两个流是否完全相等.
I want to check that the two streams are exactly equal.
我提出了几个解决方案,但看起来都不太雅致.
I've come with a couple solutions, but both seem quite inelegant.
第一个简单地将两者都转换为一个数组:
The first one simply transforms both into an array:
def equal_streams?(s1, s2)
s1.to_a == s2.to_a
end
这是可行的,但在内存方面的性能不是很好,特别是如果流有很多信息.
This works, but it is not very performant, memory-wise, specially if the streams have lots of information.
另一个选项是……呃.
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
那么,有没有更简单、更优雅的方法来做到这一点?
So, is there a simpler, more elegant way of doing this?
推荐答案
假设您的流不包含元素 :eof
,只需稍微重构您的代码.
Just a slight refactoring to your code, assuming that your streams do not include an element :eof
.
def equal_streams?(s1, s2)
loop do
e1 = s1.next rescue :eof
e2 = s2.next rescue :eof
return false unless e1 == e2
return true if e1 == :eof
end
end
使用像 loop
这样的关键字应该比使用像 each
这样的方法更快.
Using a keyword like loop
should be faster than using a method like each
.
这篇关于Ruby - 优雅地比较两个枚举器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!