views:

566

answers:

3

Is there any Ruby equivalent for Python's builtin zip function? If not, what is a concise way of doing the same thing?

A bit of context: this came up when I was trying to find a clean way of doing a check involving two arrays. If I had zip, I could have written something like:

zip(a, b).all? {|pair| pair[0] === pair[1]}

I'd also accept a clean way of doing this without anything resembling zip (where "clean" means "without an explicit loop").

+7  A: 

Ruby has a zip function:

[1,2].zip([3,4]) => [[1,3],[2,4]]

so your code example is actually:

a.zip(b).all? {|pair| pair[0] === pair[1]}

or perhaps more succinctly:

a.zip(b).all? {|a,b| a === b }
dgtized
Enumerable#zip! There it is. Thanks so much.
improper_smile
A: 

Could you not do:

a.eql?(b)
jonnii
I'm not sure. I need to use the === equivalence operator to compare elements, not ==.
improper_smile
Have you tried it?
jonnii
A: 

This is from the ruby spec:

it "returns true if other has the same length and each pair of corresponding elements are eql" do
    a = [1, 2, 3, 4]
    b = [1, 2, 3, 4]
    a.should eql(b)
    [].should eql([])
end

So you should it should work for the example you mentioned.

If you're not using integers, but custom objects I think you need to override eql?.

The spec for this method is here:

http://github.com/rubyspec/rubyspec/tree/master/1.8/core/array/eql_spec.rb

jonnii