array x array? July 18th, 2008

Tom(warning: non-english blog) had a small friday-afternoon problem for me, which they couldn’t easily figure out. The problem:

x = [1, 2, 3]
y = ['a', 'b', 'c']

???
# result should == [[1,'a'],[2,'b'],[3,'c']]

My first guess was a simple * but apparently Array#* only takes strings and numbers:

x * 3      # => [1, 2, 3, 1, 2, 3, 1, 2, 3]
x * '-'   # => "1-2-3"
x * y     # => TypeError: can't convert Array into Integer

So I went through the Array API and found out there was something like transpose. Basically this is what you want:

x = [1, 2, 3]
y = ['a', 'b', 'c']

result = [x,y].transpose
# => [[1, "a"], [2, "b"], [3, "c"]]

update! As Jean-Baptiste notes in the comments, there is also the zip function

[1, 2, 3].zip(['a', 'b', 'c']) 
# => [[1, "a"], [2, "b"], [3, "c"]]
tags: , , l

2 Responses to “array x array?”

  • 6 days ago wonko said

    Transpose isn’t that special, it sort of mirrors a matrix over its main diagonal (you can see the [x,y] array as a matrix [[1,2,3],[a,b,c]].

    More on the wikipedia page: http://en.wikipedia.org/wiki/Transpose

    multipling arrays with each other isn’t that easy when not thinking in terms of matrixes

  • 4 days ago Jean-Baptiste Escoyez said

    Actually, I think there is a method intended to do that:

    [1, 2, 3].zip([‘a’, ‘b’, ‘c’]) => [[1, “a”], [2, “b”], [3, “c”]]

    In your case, it would be an elegant:

    x.zip(y)

    You can even do

    “w.zip(x,y,z)”

    provided w, x, y and z are Arrays.

Leave a Reply