Forum: Ruby on Rails What does this method form the 2. agile book do?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Kristen (Guest)
on 2007-02-07 07:02
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!
Conrad T. (Guest)
on 2007-02-07 08:32
(Received via mailing list)
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
Conrad T. (Guest)
on 2007-02-07 08:45
(Received via mailing list)
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
Kristen (Guest)
on 2007-02-07 09:41
> 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!
This topic is locked and can not be replied to.