Home > OS >  How to stop at a specific range in ruby loops
How to stop at a specific range in ruby loops

Time:09-17

i have this piece of code here that generates a link for all of my questions from a database, but right now I have 10 entries and this loop will iterate 10 times. Is there a way to stop the iteration at a range of 4?

<table>
  <tr>
    <th>Question</th>
    <th>Button</th>
  </tr>
 </tr>
   <% @questions.each do |q| %>
  <tr>
    <td><%= q.question %></td>
    <td><%= link_to 'Question', show_url(q.id), method: :get %></td>
    <td><%= q.id %> Button</td>
    <% end %>
  </tr>
</table>

Any suggestions will be appreciated! Thanks.

CodePudding user response:

Assuming you fetch @questions from a database or other external source, e.g. in a rails controller, you could limit the number of entries when fetching your data. There are multiple ways of doing that, depending on your data retrieval method.

However, if you need to limit the questions in the ERB part of your code, you could write:

  <% @questions.take(4).each do |q| %>
    <tr>
      <td><%= q.question %></td>
      <td><%= link_to 'Question', show_url(q.id), method: :get %></td>
      <td><%= q.id %> Button</td>
    </tr>
  <% end %>

Alternatively, you could also write:

@questions[0..3]

or

@questions.first(4)

I hope you find this helpful.

  • Related