Read more

Split an array into columns

Arne Hartherz
May 11, 2011Software engineer at makandra GmbH

You know that you can collect an array as groups using in_groups or in_groups_of.

Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

Maybe you want to fetch those values in "columns" where the first value lives in the first column, the second one in the second, etc. until it wraps, so that for example the fourth value is in the first of three columns.

Put the attached file into config/initializers/ to be able to say in_columns on any Array:

>> [1, 2, 3, 4, 5, 6, 7].in_columns(3)
=> [[1, 4, 7], [2, 5], [3, 6]]

>> [1, 2, 3, 4, 5, 6, 7].in_columns(2)
=> [[1, 3, 5, 7], [2, 4, 6]]

While in_groups and in_groups_of are provided by Rails this also works in pure Ruby. If it does not for you, require 'enumerator' Show archive.org snapshot .

Posted by Arne Hartherz to makandra dev (2011-05-11 17:22)