Why does Ruby have zip and transpose when they do the same thing?

孤人 提交于 2019-12-21 09:39:15

问题


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?


回答1:


#transpose Assumes that self is an array of arrays and transposes the rows and columns.

#zip assumes self can be any Enumerable object.

More differences are here

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]]

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.

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.



来源:https://stackoverflow.com/questions/21455310/why-does-ruby-have-zip-and-transpose-when-they-do-the-same-thing

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