# .each looping too many times

**URL:** <https://www.ruby-forum.com/t/each-looping-too-many-times/180185>\
**Category:** Rails\
**Created:** [December 14, 2009, 9:39am UTC](https://www.ruby-forum.com/t/each-looping-too-many-times/180185 "2009-12-14T09:39:01Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![aftershock](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/8e7dd6/32.png) [@aftershock](https://www.ruby-forum.com/u/aftershock)\
**Post date:** [December 14, 2009, 9:39am UTC](https://www.ruby-forum.com/t/each-looping-too-many-times/180185/1 "2009-12-14T09:39:01Z")

</div>

logger.debug("@@@@ - line item count is #{order.line\_items.count}")  
order.line\_items.each\_with\_index do |line\_item, index|  
logger.debug("@@@@ - line item")  
request.memo += “#{line\_item.order\_quantity} x  
#{line\_item.product\_name}”

# if index \< order.line\_items.count

```
  request.memo += ', '

```

# end

end

This twice for each line item  
order is an activerecord object and line\_items is an array of active  
record objects

The ouptut from the above looks like this  
@@@@ - line item count is 3  
@@@@ - line item  
@@@@ - line item  
@@@@ - line item  
@@@@ - line item  
@@@@ - line item  
@@@@ - line item

and the text in request.memo looks like this  
Payment for Order Number 6 for the following items 1 x ff, 1 x ff, 1 x  
ggffggff, 1 x ggffggff, 1 x 10, 1 x 10,

So it looks like the loop is iterating twice for each line\_item

The count shows there are only three line items and there are only 3  
records in the line items table attached to the order.  
The same happens with .each as well and the index only ever reaches the  
number 3 which is why I commented out the if index check.

I’m guessing that the problem is not with the loop but with the order  
object but I can’t think how this could be an issue or what to check  
for.
