Rockwell Rice
Rockwell Rice

Reputation: 3002

how to get key in ruby on rails .each loop

In laravel I am use to being able to access the key in a loop. In rails I cannot find answer to how to get that from the loop.

Standard loop like so

<% @subjects.each do |subject| %>

   <div class="col-md-6 subjectColumn">
       <div class="subjectBox subjectBox-<%= key %>">
           <h2><%= subject.title.capitalize %><h2> 
           <p><%= subject.description %></p>


           <a href="/subjects/<%= subject.id %>">View courses<i class="fa fa-angle-right"></i></a></h2>
       </div>

   </div>

<% end %>

I want to add the integer for the key in the code above. I have tried...

<% @subjects.keys.each do |key, subject|

...and other various things I found here and elsewhere but nothing worked. The above code created an error. Most of the things I found just did not give any number. Any help with this would be greatly appreciated. I feel I probably just have not got the syntax quite correct or something.

Upvotes: 0

Views: 847

Answers (1)

Nic Nilov
Nic Nilov

Reputation: 5156

Use with_index:

<% @subjects.each.with_index(1) do |subject, index| %>

   <div class="col-md-6 subjectColumn">
       <div class="subjectBox subjectBox-<%= index %>">
           <h2><%= subject.title.capitalize %><h2> 
           <p><%= subject.description %></p>


           <a href="/subjects/<%= subject.id %>">View courses<i class="fa fa-angle-right"></i></a></h2>
       </div>

   </div>

<% end %>

Upvotes: 1

Related Questions