1

I'm trying to return some json to the calling action. One of the params I want to pass is an array of arrays built from looping through a collection as so:

render :json => {     
:rows => @classrooms.each do |classroom|
          [classroom.name, classroom.students.count]
        end    
}  

However, this sets :rows to the entire collection as opposed to what I want:

[[classroom, students],[classroom, students],[classroom, students]]

Is there any way of looping through the collection and returning an array in a single block?

2 Answers 2

4

Enumerable#map is the right tool here.

render :json => {
  :rows => @classrooms.map {|c| [c.name, c.students.count]}
}
Sign up to request clarification or add additional context in comments.

1 Comment

Indeed, I keep forgetting about all the enumerable mixin methods!
0

Another approach... each_with_object method:

render :json => {     
:rows => @classrooms.each_with_object([]) do |classroom, a|
          a << [classroom.name, classroom.students.count]
        end    
}  

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.