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

[亡魂溺海] 提交于 2019-12-22 01:38:16

问题


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


回答1:


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 }



回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/263623/what-is-a-ruby-equivalent-for-pythons-zip-builtin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!