keyan.r keyan.r - 1 year ago 65
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

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

Answer Source

You will be using Array#zip for it like:

names = %w(name1 name2 name3)
slugs = %w(slug1 slug2 slug3)
# [["name1", "slug1"], ["name2", "slug2"], ["name3", "slug3"]]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download