keyan.r keyan.r - 5 months ago 7
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.name, x.slug] } %>


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

Answer

Use << instead of +=:

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

Or even better use the Ruby idiom map:

schoolSelect = @schools.map { |s| [s.name, s.slug] }

This works, because map already returns an array.