What is a Ruby equivalent for Python's “zip” builtin?
-
06-07-2019 - |
Question
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").
Solution
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 }
OTHER TIPS
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
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