I've got two long streams of numbers coming from two different sources (binary data) in Ruby (1.9.2).
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.
The other option is... ugh.
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?
zip
is that it creates arrays internally, no matter what Enumerable you pass. There's another problem with length of input params. – Viniculturezip
actually always returns an array of arrays (can be seen in the docs), which means that it will internally "uncoil" any passed Enumerable, even a lazy one (such as generator), into an array. I hadn't actually dived into YARV source. I have implemented something similar which works lazily and returns an Enumerator here, but it's not perfect fit for this question either. – Viniculture1.times.zip(1.times) {|x,y| puts x, y; 42}
prints out 0, 0 and returnsnil
. – Podiumzip
. Not sure how it can be used though, as it looks to me that block-form ofzip
can be used only ineach
-like context, not passed around as a new Enumerable (so it could be for exampleall?
-ed)? – Viniculture