keyan.r keyan.r - 9 months ago 28
Ruby Question

(Ruby) how to insert a pair into an array

I have a 2D array that is to have the name and slug of each school in a database, as pairs.
I want to start this array off empty and then add each school one-by-one to it.

This is what I have tried:

<% schoolSelect = [] %>
<% @schools.each { |x| schoolSelect += [, x.slug] } %>

However, this adds the name and slug of a school into the array in session, instead of two-dimensional.


Use << instead of +=:

schoolSelect = []
@schools.each { |x| schoolSelect << [, x.slug] }

Or even better use the Ruby idiom map:

schoolSelect = { |s| [, s.slug] }

This works, because map already returns an array.