0

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.

7
  • what is inside the @schools and what you want in output plz tell Commented Jul 4, 2016 at 15:23
  • You are still using the code snippet instead of normal code block. Please stop using it unless you have a runnable exemple to show. Commented Jul 4, 2016 at 15:23
  • Why do you want to do that? It feels to me like you are going to use that array in a select? If that is the case there might be better solutions, since there are quite clever form builder methods. Commented Jul 4, 2016 at 15:24
  • 1
    @Marc-Andre apologies, edited above, let me know if it's correct now. Commented Jul 4, 2016 at 15:26
  • 1
    @keyan.r It's correct, thank you for modifying it. It take less space in your question now. Commented Jul 4, 2016 at 15:27

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.