keyan.r
keyan.r

Reputation: 137

(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.

Upvotes: 0

Views: 225

Answers (1)

spickermann
spickermann

Reputation: 107142

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.

Upvotes: 3

Related Questions