theillien
theillien

Reputation: 1380

How do I iterate over an array and output each iteration?

Suppose my array looks like this:

People => [
  {
    Person => Jack,
    Age => 25
  },
  {
    Person => Frank,
    Age => 45
  },
  {
    Person => Molly,
    Age => 30
  }
]

I thought that iteration code would be in the controller since it is handling data. My controller code looks like this:

class People < ApplicationController
  def list
    people.each do |hash|
      @person = hash[person]
      @age = hash[age]
    end
  end
end

My view code looks like:

<h1>People</h1>
<p>
  Person: <%= @person %> <br/>
  Age: <%= @age %> <br/>
  <br/>
</p>

When I load the page, rather than seeing three blocks of output, one for each person, I only see one block for Molly: the last iteration.

I'm thinking I need to put the iteration code in the view rather than the controller. Is this correct?

Upvotes: 0

Views: 92

Answers (2)

kempchee
kempchee

Reputation: 470

Every time you loop through you are resetting the @person, @age instance variables. That is why you are left with only the last person. Assuming the person information is stored in your database, you should load all people with:

#controller
@people=Person.all

#then in the view
<h1>People</h1>
<%@people.each do |person|%>    
  <p>
   Person: <%=person.person %> <br/>
   Age: <%= person.age %> <br/>
  <br/>
  </p>
<%end%>

Upvotes: 0

derekyau
derekyau

Reputation: 2946

Yes, what happens is that when you set an instance variable ie. @person in a controller, it automatically gets thrown to the view. In this case, your code is overwriting @person with the last person that is available.

As you mentioned, put the loop in the view instead like so:

<h1>People</h1>
<% @people.each do |person| %>
  <p>
    Age: <%= person.age %> <br/>
    <br/>
  </p>
<% end %>

(this is assuming you set an instance variable called @people, eg. @people = Person.all)

Upvotes: 4

Related Questions