简体   繁体   中英

What is a Ruby equivalent for Python's “zip” builtin?

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

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 }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM