If I have the following,
<% @feed.sort_by{|t| - t.created_at.to_i}.each do |feed| %>
<% end %>
How can limit it to only show the 10 most recent results
If I have the following,
<% @feed.sort_by{|t| - t.created_at.to_i}.each do |feed| %>
<% end %>
How can limit it to only show the 10 most recent results
<% @feed.sort_by{|t| - t.created_at.to_i}.first(10).each do |feed| %>
However, it's probably best to push this down into the model like this
<% @feed.recent(10).each do |feed| %>
And, in fact, if @feed
comes out of a database, I'd push it down even further: it doesn't make sense to load a ton of unsorted feed entries out of the DB, then sort them and then throw most of them away. Better let the DB do the sorting and filtering.
See @Peer Allan's answer for how to do it in ActiveRecord
. In ARel
(IOW: Rails 3) it would probably be even simpler, something like
Feed.all.order('created_at DESC').take(10)
I agree with the others (Jörg in particular); but if you still want to know how to limit the loop itself, break
can be useful.
@array.each_with_index do |feed, i|
break if i == 10;
# ...
The created_at seems to indicate that you are using ActiveRecord in Rails to get set the @feed variable. If that is the case you are better to do this work in SQL. Its far more efficient and easier to deal with.
@feed = Feed.all(:order => 'created_at DESC', :limit => 10)
Otherwise if you really want to use the view to do this you can use first or a range
<% @feed.sort_by{|t| - t.created_at.to_i}[0..9].each do |feed| %>
<% @feed.sort_by{|t| - t.created_at.to_i}.first(10).each do |feed| %>