Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit each do loop

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

like image 224
Karl Entwistle Avatar asked Jul 07 '10 02:07

Karl Entwistle


People also ask

How do you put a limit in a for loop?

An easy way to go about this would be to put the user-input prompt inside of a while loop, and only break out once you've verified that the grade is valid: Scanner scanner = new Scanner(System.in); int score; while (true) { System. out. print("Please enter score " + (g + 1) + ": "); score = scanner.

How do you limit a loop in Python?

zip(range(limit), items) Using Python 3, zip and range return iterables, which pipeline the data instead of materializing the data in lists for intermediate steps. To get the same behavior in Python 2, just substitute xrange for range and itertools. izip for zip .

How do you stop a loop in Ruby?

In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly used in while loop, where value is printed till the condition, is true, then break statement terminates the loop. In examples, break statement used with if statement. By using break statement the execution will be stopped.

Is there a for loop in Ruby?

In Ruby, for loops are used to loop over a collection of elements.


2 Answers

<% @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) 
like image 142
Jörg W Mittag Avatar answered Sep 28 '22 00:09

Jörg W Mittag


Array#first(n)

[1,2,3,4,5].first(3) => [1,2,3] 
like image 39
Bryan Ash Avatar answered Sep 27 '22 23:09

Bryan Ash