Ruby(1.9.2)の2つの異なるソース(バイナリデータ)からの2つの長い数値ストリームがあります。
2つのソースは、2つの列挙子の形式でカプセル化されます。
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
それで、これを行うためのより簡単でよりエレガントな方法はありますか?