Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 497
Jumbalaya Wanton Avatar asked Jan 30 '14 11:01

Jumbalaya Wanton


People also ask

What does zip do in Ruby?

Ruby | Array zip() function Array#zip() : zip() is a Array class method which Converts any arguments to arrays, then merges elements of self with corresponding elements from each argument. Return: merges elements of self with corresponding elements from each argument.

What is transpose Ruby?

Ruby | Array transpose() function Array#transpose() : transpose() is a Array class method which returns the length of elements in the array transposes the rows and columns.

How to get value from array in Ruby?

Elements in an array can be retrieved using the #[] method. It can take a single integer argument (a numeric index), a pair of arguments (start and length) or a range. Negative indices start counting from the end, with -1 being the last element. The slice method works in an identical manner to #[].


1 Answers

#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.

like image 154
Arup Rakshit Avatar answered Nov 08 '22 18:11

Arup Rakshit