![](/img/trans.png)
[英]Python: What's the fastest way to zip right to left, and is there no builtin for this?
[英]What is a Ruby equivalent for Python's “zip” builtin?
Python的内置zip
功能是否有Ruby等价物? 如果没有,做同样事情的简洁方法是什么?
一点上下文:当我试图找到一个干净的方法来检查涉及两个数组时,就会出现这种情况。 如果我有zip
,我可以写下这样的东西:
zip(a, b).all? {|pair| pair[0] === pair[1]}
我也接受一种干净的方式来做这个没有类似zip
东西(其中“干净”意味着“没有明确的循环”)。
Ruby有一个zip功能:
[1,2].zip([3,4]) => [[1,3],[2,4]]
所以你的代码示例实际上是:
a.zip(b).all? {|pair| pair[0] === pair[1]}
或者更简洁:
a.zip(b).all? {|a,b| a === b }
你不能这样做:
a.eql?(b)
编辑添加一个例子:
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
这是来自ruby规范:
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
所以你应该为你提到的例子工作。
如果你不是使用整数,而是自定义对象,我认为你需要覆盖eql?。
此方法的规范如下:
http://github.com/rubyspec/rubyspec/tree/master/1.8/core/array/eql_spec.rb
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.