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 comments »