Loop in Ruby on Rails html.erb file

Stark_kids picture Stark_kids · Jul 3, 2014 · Viewed 46.7k times · Source

everybody I'm brand new with Ruby on Rails and I need to understand something. I have an instance variable (@users) and I need to loop over it inside an html.erb file a limitated number of times. I already used this:

<% @users.each do |users| %>
   <%= do something %>
<%end %>

But I need to limitate it to, let's say, 10 times. What can I do?

Answer

infused picture infused · Jul 3, 2014

If @users has more elements than you want to loop over, you can use first or slice:

Using first

<% @users.first(10).each do |users| %>
  <%= do something %>
<% end %>

Using slice

<% @users.slice(0, 10).each do |users| %>
  <%= do something %>
<% end %>

However, if you don't actually need the rest of the users in the @users array, you should only load as many as you need by using limit:

@users = User.limit(10)