为什么红宝石有拉链,当他们做同样的事情转? [英] Why does Ruby have zip and transpose when they do the same thing?

查看:109
本文介绍了为什么红宝石有拉链,当他们做同样的事情转?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

他们似乎做同样的事情。

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 假定可以是任何的 可枚举 对象。

#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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆