9

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?

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
Jumbalaya Wanton
  • 1,601
  • 1
  • 25
  • 47
  • 10
    They do the same thing on *those particular inputs*. – Colonel Panic Jan 30 '14 at 11:34
  • 13
    Per what @ColonelPanic says, you can't draw the conclusion that they're the same when you are only looking at a trivial example. It's a bit like asking why Ruby has both `*` and `+` since `2+2` and `2*2` do the same thing. – lurker Jan 30 '14 at 11:41
  • 1
    @mbratch Thanks for making me feel stupid. Well put! :D – Jumbalaya Wanton Jan 30 '14 at 11:41
  • 2
    @JumbalayaWanton haha not intended. I'm just prodding a little more exploration on your part. :) One major characteristic of Ruby is that when you want to do something, there are often several different ways to do it that can achieve the same result. Some ways are more "canonical" or semantically appropriate than others. – lurker Jan 30 '14 at 11:43

1 Answers1

14

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

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317