# What does this method form the 2. agile book do?

**URL:** <https://www.ruby-forum.com/t/what-does-this-method-form-the-2-agile-book-do/84717>\
**Category:** Rails\
**Created:** [February 7, 2007, 6:02am UTC](https://www.ruby-forum.com/t/what-does-this-method-form-the-2-agile-book-do/84717 "2007-02-07T06:02:29Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Kristen](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/c4cdca/32.png) [@Kristen](https://www.ruby-forum.com/u/Kristen)\
**Post date:** [February 7, 2007, 6:02am UTC](https://www.ruby-forum.com/t/what-does-this-method-form-the-2-agile-book-do/84717/1 "2007-02-07T06:02:29Z")

</div>

def add\_product(product)  
current\_item = @items.find {|item| item.product == product}  
if current\_item  
current\_item.increment\_quantity  
else  
@items \<\< CartItem.new(product)  
end

Im constantly getting errors when adding this into my code. Does anyonw  
know whats wrong with it?

Also, can soemone please explain what the second line in the code does:  
current\_item = @items.find {|item| item.product == product}

Thanks in advance!

---

<div class="post-metadata">

**Author:** ![Kristen](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/c4cdca/32.png) [@Kristen](https://www.ruby-forum.com/u/Kristen)\
**Post date:** [February 7, 2007, 7:32am UTC](https://www.ruby-forum.com/t/what-does-this-method-form-the-2-agile-book-do/84717/2 "2007-02-07T07:32:54Z")

</div>

Hi Kristen, the second line searches for a product within the within  
the collection of current products. That is

@items.find { |item| item.product == product }

or you can write it as follows

for each item in @items

if item.product == product  
current\_item = item  
break  
end

end

Lastly, it seems that you missing an ‘end’ of the last line of the  
method.

Good luck,

-Conrad

---

<div class="post-metadata">

**Author:** ![Kristen](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/c4cdca/32.png) [@Kristen](https://www.ruby-forum.com/u/Kristen)\
**Post date:** [February 7, 2007, 7:45am UTC](https://www.ruby-forum.com/t/what-does-this-method-form-the-2-agile-book-do/84717/3 "2007-02-07T07:45:56Z")

</div>

Hi, the for loop should read…

for item in @items # no each within a ruby for loop

if item.product == product  
current\_item = item  
break  
end

end

-Conrad

---

<div class="post-metadata">

**Author:** ![Kristen](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/c4cdca/32.png) [@Kristen](https://www.ruby-forum.com/u/Kristen)\
**Post date:** [February 7, 2007, 8:41am UTC](https://www.ruby-forum.com/t/what-does-this-method-form-the-2-agile-book-do/84717/4 "2007-02-07T08:41:49Z")

</div>

> Lastly, it seems that you missing an ‘end’ of the last line of the  
> method.

Thanks. That did the trick. I also replaced the second line with the  
much simpler for loop. Thanks again guys!
