19

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").

Eric Naeseth
  • 2,293
  • 2
  • 19
  • 18

3 Answers3

28

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
  • 3,192
  • 2
  • 24
  • 23
0

Could you not do:

a.eql?(b)

Edited to add an example:

a = %w[a b c]
b = %w[1 2 3]
c = ['a', 'b', 'c']

a.eql?(b) # => false
a.eql?(c) # => true
a.eql?(c.reverse) # => false
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
jonnii
  • 28,019
  • 8
  • 80
  • 108
-2

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
  • 28,019
  • 8
  • 80
  • 108