keyan.r keyan.r - 5 months ago 13
Ruby Question

How to combine one-dimensional ruby arrays into a two-dimensional array?

I have two arrays:


  • array of school names

  • array of school slugs



Say the array of school names is:
[name1, name2, name3]
and of slug names are:
[slug1, slug2, slug3]
.

In ruby, how would I make an array
[[name1, slug1], [name2, slug2], [name3, slug3]]
.

My attempt at the matter is kind of
javascript-ish
:

<% var schoolSelect = [];
for (var i=0; i<@schools.length; i++)
schoolSelect[i] = [@schools.pluck(:name)[i], @schools.pluck(:slug)[i]]; %>

Answer

You will be using Array#zip for it like:

names = %w(name1 name2 name3)
slugs = %w(slug1 slug2 slug3)

names.zip(slugs)
# [["name1", "slug1"], ["name2", "slug2"], ["name3", "slug3"]]
Comments