From: Josh Cheek Date: 2011-11-28T00:16:25+09:00 Subject: Re: Creating 2-D array from 1-D array --0015174413d07c1cb204b2b8de4d Content-Type: text/plain; charset=ISO-8859-1 On Sun, Nov 27, 2011 at 7:06 AM, J. Marshal 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 # => # # 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]] --0015174413d07c1cb204b2b8de4d--