# Database query and loops

**URL:** <https://www.ruby-forum.com/t/database-query-and-loops/178096>\
**Category:** Rails\
**Created:** [October 29, 2009, 1:25am UTC](https://www.ruby-forum.com/t/database-query-and-loops/178096 "2009-10-29T01:25:31Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![biqut2](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/f475e1/32.png) [@biqut2](https://www.ruby-forum.com/u/biqut2)\
**Post date:** [October 29, 2009, 1:25am UTC](https://www.ruby-forum.com/t/database-query-and-loops/178096/1 "2009-10-29T01:25:31Z")

</div>

Quick question, for example if you have in your controller:

@users = User.all  
for user in @users

# blah blah blah

end

what is the best and most strait forward method to find out if you  
have reached the last user in @users?

---

<div class="post-metadata">

**Author:** ![biqut2](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/f475e1/32.png) [@biqut2](https://www.ruby-forum.com/u/biqut2)\
**Post date:** [October 29, 2009, 1:34am UTC](https://www.ruby-forum.com/t/database-query-and-loops/178096/2 "2009-10-29T01:34:53Z")

</div>

On Oct 28, 2009, at 5:23 PM, h3avyarms wrote:

> Quick question, for example if you have in your controller:
> 
> @users = User.all  
> for user in @users

if user == @users.last

# do something with the last user

end

> # blah blah blah
> 
> end
> 
> what is the best and most strait forward method to find out if you  
> have reached the last user in @users?

If you don’t want that check in there you could also do…

@users = User.all  
last\_user = @users.pop  
for user in @users  
#…  
end

# do something with last\_user

-philip

---

<div class="post-metadata">

**Author:** ![biqut2](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/f475e1/32.png) [@biqut2](https://www.ruby-forum.com/u/biqut2)\
**Post date:** [October 29, 2009, 1:44am UTC](https://www.ruby-forum.com/t/database-query-and-loops/178096/3 "2009-10-29T01:44:15Z")

</div>

Thank you for the fast response, I was resorting to using if  
statements in my current setup and the last\_user = @users.pop solution  
is much cleaner and should actuolly run faster for really large  
loops.
