为什么红宝石有拉链,当他们做同样的事情转? [英] Why does Ruby have zip and transpose when they do the same thing?
问题描述
他们似乎做同样的事情。
They seem to do the same thing.
g = [{ a: "A" }, { b: "B" }]
r = [{ x: "X" }, { y: "Y" }]
g.zip(r) # => [[{:a=>"A"}, {:x=>"X"}], [{:b=>"B"}, {:y=>"Y"}]]
[g,r].transpose # => [[{:a=>"A"}, {:x=>"X"}], [{:b=>"B"}, {:y=>"Y"}]]
为什么有两种方法?
Why have both methods?
推荐答案
的 #transpose
的假设自我为一个数组的数组并调换的行和列。的
#transpose
Assumes that self is an array of arrays and transposes the rows and columns.
#zip
assumes self
can be any Enumerable
object.
更多的差异在这里
a = [12,11,21]
b = [1,2]
[a,b].transpose # transpose': element size differs (2 should be 3) (IndexError)
a.zip(b) # => [[12, 1], [11, 2], [21, nil]]
b.zip(a) # => [[1, 12], [2, 11]]
这是应用 #transpose
方法 A
和 B
应该是相同大小的。但申请 #zip
,它不需要 B
是的同样大小的一个
,即 b
和 A
可以是任意大小的。
That to apply the #transpose
method a
and b
should be of the same size. But for applying #zip
, it is not needed b
to be of the same size of a
, ie b
and a
can be of any of size.
使用 #zip
时,所得的阵列的大小总是会自我的大小
。随着 #transpose
所产生的阵列的规模将是任何自我的内阵列的大小
With #zip
, the resultant array size will always be the size of self
. With #transpose
the resulting array size will be any of the inner array's size of self
.
这篇关于为什么红宝石有拉链,当他们做同样的事情转?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!