You can also use Hash constructor:

a = [1 , 2 , 3 , 4 , 5 , 6]
siliced = Hash[*a].to_a

Sandro


On Sunday, November 27, 2011, Josh Cheek <josh.cheek / gmail.com> wrote:
> On Sun, Nov 27, 2011 at 7:06 AM, J. Marshal <windbreiz / gmail.com> wrote:
>
>> Hello, I am relatively new to Ruby.  I have an existing array:
>>   a = [1 , 2 , 3 , 4 , 5 , 6]
>> and I want to create this 2-D array:
>>   b = [[1 , 2][2 , 4][5 , 6]]
>> I am using the following code, which works, but seems somewhat clumsy:
>>    b = Array.new
>>    i = 0
>>    k = 0
>>    for item in a
>>      if i == 0
>>        a1 = item
>>        i = 1
>>      elsif i == 1
>>        a2 = item
>>        i = 0
>>        b[k] = [a1, a2]
>>        puts "b..#{k},  #{b[k]}"
>>        k = k + 1
>>      end
>>    end
>> I would appreciate any advice to make this code look more elegant or
>> ruby-like.  In particular, I suspect there is a way to avoid the
>> indices.
>> Thanks for the help.
>>
>> --
>> Posted via http://www.ruby-forum.com/.
>>
>>
>
> # There are some very helpful methods in Enumerable
> # (http://rubydoc.info/stdlib/core/1.9.3/Enumerable).
> # In this case, check out each_slice.
>
> ary = [1 , 2 , 3 , 4 , 5 , 6]
> sliced = ary.each_slice 2
>
> sliced # => #<Enumerator: [1, 2, 3, 4, 5, 6]:each_slice(2)>
>
>
>
> # You can think of it like the array you showed,
> # for instance you can iterate over its elements
> # or map them to new values or whatever.
>
> sliced.each do |element|
>  element # => [1, 2], [3, 4], [5, 6]
> end
>
> sliced.map(&:reverse) # => [[2, 1], [4, 3], [6, 5]]
>
>
>
> # But if you really need an array, you can get it with to_a
>
> sliced.to_a # => [[1, 2], [3, 4], [5, 6]]
>